2020年11月19日:
JdbcTemplate实现增删改
API介绍
org.springframework.jdbc.core.JdbcTemplate
类方便执行SQL语句
-
public int update(final String sql) 用于执行`INSERT`、`UPDATE`、`DELETE`等DML语句。
使用步骤
1.创建JdbcTemplate对象
2.编写SQL语句
3.使用JdbcTemplate对象的update方法进行增删改查
案例代码
public class Demo05 {
public static void main(String[] args) throws Exception {
// test01();
// test02();
// test03();
}
// JDBCTemplate添加数据
public static void test01() throws Exception {
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
String sql = "INSERT INTO product VALUES (NULL, ?, ?);";
jdbcTemplate.update(sql, "iPhone3GS", 3333);
jdbcTemplate.update(sql, "iPhone4", 5000);
jdbcTemplate.update(sql, "iPhone4S", 5001);
jdbcTemplate.update(sql, "iPhone5", 5555);
jdbcTemplate.update(sql, "iPhone5C", 3888);
jdbcTemplate.update(sql, "iPhone5S", 5666);
jdbcTemplate.update(sql, "iPhone6", 6666);
jdbcTemplate.update(sql, "iPhone6S", 7000);
jdbcTemplate.update(sql, "iPhone6SP", 7777);
jdbcTemplate.update(sql, "iPhoneX", 8888);
}
// JDBCTemplate修改数据
public static void test02() throws Exception {
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
String sql = "UPDATE product SET pname=?, price=? WHERE pid=?;";
int i = jdbcTemplate.update(sql, "XVIII", 18888, 10);
System.out.println("影响的行数: " + i);
}
// JDBCTemplate删除数据
public static void test03() throws Exception {
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
String sql = "DELETE FROM product WHERE pid=?;";
int i = jdbcTemplate.update(sql, 7);
System.out.println("影响的行数: " + i);
}
}