JDBCtemplate是对JDBC的封装,能够极大减少在使用过程中的代码冗余,减少一些不必要的操作如连接的创建和关闭。
建表
```
public class Demo {
public static void main(String[] args) {
String sql = "CREATE TABLE Goods("
+ "pid INT PRIMARY KEY,"
+ "pname VARCHAR(20),"
+ "price DOUBLE"
+ ");";
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
jdbcTemplate.execute(sql);
}
}
```
增删改
`
// JDBCTemplate添加数据
public static void test01() throws Exception {
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
String sql = "INSERT INTO Goods VALUES (NULL, ?, ?);";
jdbcTemplate.update(sql, "apple", 2);
jdbcTemplate.update(sql, "banana",1);
}
// JDBCTemplate修改数据
public static void test02() throws Exception {
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
String sql = "UPDATE product SET pname=?, price=? WHERE pid=?;";
jdbcTemplate.update(sql, "apple", 3, 1);
}
// JDBCTemplate删除数据
public static void test03() throws Exception {
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
String sql = "DELETE FROM product WHERE pid=?;";
jdbcTemplate.update(sql, 1);
}
}
`
查
```
public static void test() throws Exception {
String sql = "SELECT pname FROM product WHERE price=3;";
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
String str = jdbcTemplate.queryForObject(sql, String.class);
}
```
这里的string.class里的string可以使用BeanPropertyRowMapper将数据库查询结果转换为Java类对象。