brief introduction
JdbcTemplate is Spring's encapsulation of JDBC to make JDBC easier to use. The JdbcTemplate is part of Spring. The JdbcTemplate handles the creation and release of resources. He helps us avoid some common mistakes, such as forgetting to always close the connection.
The methods of executing SQL statements in the JdbcTemplate can be roughly divided into three categories:
- Execute: all SQL statements can be executed without return value. It is generally used to execute DDL statements.
- Update: returns the number of affected rows, which is used to execute DML statements such as INSERT, update, DELETE, etc.
- queryXxx: used for DQL data query statements such as SELECT.
common method
public void execute(final String sql); public int update(final String sql); public int queryForInt(String sql); public long queryForLong(String sql); public <T> T queryForObject(String sql, Class<T> requiredType); public Map<String, Object> queryForMap(String sql); public List<Map<String, Object>> queryForList(String sql); public <T> List<T> query(String sql, RowMapper<T> rowMapper); public class BeanPropertyRowMapper<T> implements RowMapper<T>;
Use example
jdbcTemplate.execute("CREATE TABLE product...;"); public int update("INSERT INTO product VALUES (NULL, ?, ?);", "iPhoneX", 8888); public int queryForInt("SELECT id FROM product WHERE price=8888;"); public long queryForLong("SELECT COUNT(*) FROM product;"); public String queryForObject("SELECT pname FROM product WHERE price=7777;", String.class); public Map<String, Object> queryForMap("SELECT * FROM product WHERE id=?;", 6); public List<Map<String, Object>> queryForList("SELECT * FROM product WHERE pid<?;", 8); public List<Product> query("SELECT * FROM product;", new RowMapper<Product>() {...}); public List<Product> query("SELECT * FROM product;", new BeanPropertyRowMapper<>(Product.class));
reference resources: https://blog.csdn.net/weixin_40001125/article/details/88538576