外围办法
update(Connection conn, String sql, Object...params)
参数 | 阐明 |
---|---|
Connection conn | 数据库连贯对象 |
String sql | 占位符模式的SQL |
Object...param | Object类型的数组(或繁多数据),用来设置占位符上的参数 |
Connection conn
: 主动模式创立QueryRunner对象时无需提供,手动模式创立时必须提供String sql
: 应用?进行占位
步骤概述
- 创立QueryRunner对象(手动或主动)
- 占位符形式编写SQL
- 设置占位符参数
- 执行
代码示例
/** * 我的项目形容: 应用QueryRunner类执行增删改操作 * 作 者: chain.xx.wdm */public class QueryRunnerInsertTest { /** * 应用无参形式结构QueryRunner对象,即手动模式,向数据表中插入数据 * */ @Test public void insertTest(){ Connection connection = null; try { // 1.应用无参形式结构QueryRunner的对象 QueryRunner queryRunner = new QueryRunner(); // 2.获取连贯 connection = DruidUtils.getConnection(); // 3.应用占位符形式编写sql语句 String sql = "insert into employee values (?,?,?,?,?,?)"; // 4.创立Object类型的数组,元素内容是要替换占位符的数据 Object[] param = {null,"张百万",25,"男",5000,"2019-11-11"}; // 5.执行sql语句 queryRunner.update(connection,sql,param); } catch (SQLException throwables) { throwables.printStackTrace(); } finally { // 6.敞开对象 DbUtils.closeQuietly(connection); } } /** * 应用无参形式结构QueryRunner对象,即手动形式批改数据 * */ @Test public void updateTest(){ Connection connection = null; try { // 1.应用无参形式结构QueryRunner对象 QueryRunner queryRunner = new QueryRunner(); // 2.获取连贯 connection = DruidUtils.getConnection(); // 3.编写占位符模式sql语句 String sql = "update employee set salary = ? where ename = ?"; // 4.创立Object数组,数组元素是替换占位符的数据 Object[] param = {5555,"张百万"}; // 5.执行更新操作 queryRunner.update(connection,sql,param); } catch (SQLException throwables) { throwables.printStackTrace(); } finally { // 6.敞开对象 DbUtils.closeQuietly(connection); } } /** * 应用有参形式结构QueryRunner对象,即主动模式实现删除数据 * */ @Test public void deleteTest(){ try { // 1。应用有参形式结构QueryRunner对象 QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource()); // 2。创立占位符模式的sql语句 String sql = "delete from employee where eid = ?"; // 3。创立Object类型数组,数组内元素是替换占位符的数值 //Object[] param = {3}; // 只有一个占位符,能够不应用数组 // 3。执行更新操作 queryRunner.update(sql,1); } catch (SQLException throwables) { throwables.printStackTrace(); } }}