核心方法
update(Connection conn, String sql, Object... params)
参数 | 说明 |
Connection conn | 数据库连接对象, 自动模式创建QueryRun 可以不传 ,手动模式必须传递 |
String sql | 占位符形式的SQL ,使用 ? 号占位符 |
Object... param | Object类型的 可变参,用来设置占位符上的参数 |
步骤
1.创建QueryRunner(手动或自动)
2.占位符方式 编写SQL
3.设置占位符参数
4.执行
添加
@Test
public void testInsert() throws SQLException {
//1.创建 QueryRunner 手动模式创建
QueryRunner qr = new QueryRunner();
//2.编写 占位符方式 SQL
String sql = "insert into employee values(?,?,?,?,?,?)";
//3.设置占位符的参数
Object[] param = {null,"张百万",20,"女",10000,"1990-12-26"};
//4.执行 update方法
Connection con = DruidUtils.getConnection();
int i = qr.update(con, sql, param);
//5.释放资源
DbUtils.closeQuietly(con);
}
修改
//修改操作 修改姓名为张百万的员工工资
@Test
public void testUpdate() throws SQLException {
//1.创建QueryRunner对象 自动模式,传入数据库连接池
QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
//2.编写SQL
String sql = "update employee set salary = ? where ename = ?";
//3.设置占位符参数
Object[] param = {0,"张百万"};
//4.执行update, 不需要传入连接对象
qr.update(sql,param);
}
删除
//删除操作 删除id为1 的数据
@Test
public void testDelete() throws SQLException {
QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
String sql = "delete from employee where eid = ?";
//只有一个参数,不需要创建数组
qr.update(sql,1);
}