In Spring, how can I insert data in table using JdbcTemplate. Can anyone please provide me a code sample for doing this.
Create a new JdbcTemplate object, with the given datasource to obtain connections from. Use the update(String sql, Object args, int[] argTypes) API method of JdbcTemplate , to issue the SQL insert operation via a prepared statement, binding the given arguments.
The spring jdbctemplate internally invokes the java. sql executeUpdate method, which can execute an insert , update, delete or ddl statements.
Use the queryForList(String sql) API method of JdbcTemplate class to execute a query for a result list, with the given static SQL select query. The results will be mapped to a List (one entry for each row) of result objects, each of them matching the specified element type.
Use jdbcTemplate.update(String sql, Object... args)
method:
jdbcTemplate.update( "INSERT INTO schema.tableName (column1, column2) VALUES (?, ?)", var1, var2 );
or jdbcTemplate.update(String sql, Object[] args, int[] argTypes)
, if you need to map arguments to SQL types manually:
jdbcTemplate.update( "INSERT INTO schema.tableName (column1, column2) VALUES (?, ?)", new Object[]{var1, var2}, new Object[]{Types.TYPE_OF_VAR1, Types.TYPE_OF_VAR2} );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With