JDBC | 第二章: JDBC之批量更新,添加,和删除操作
在JDBC中Statement批量操作主要用到了addBatch批量添加要执行的sql到当前Statement对象 executeBatch提交执行所有sql语句
批量添加#
public int[] insBatch() {
Connection connection = null;
Statement statement = null;
String sql = "";
try {
//获取数据连接
connection = basicUse.getConnection();
//获取发送sql指令执行sql对象
statement = connection.createStatement();
for (int i = 0; i < 10; i++) {
StringBuffer sbf = new StringBuffer("insert into student (name, age, addr, hobby) ");
sbf.append(" values ('kenx',24,'上海','篮球')");
sql = sbf.toString();
System.out.println("执行sql" + sql);
//将指定SQL添加到Statement对象的当前命令列表中
statement.addBatch(sql);
}
//执行成功返回更新计数的数组
int[] success = statement.executeBatch(); //批量执行所有sql返回一个更新计数的数组
return success;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
//执行完数据库操作后记得关闭数据库连接资源
try {
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
批量更新#
public int[] updBatch() {
Connection connection = null;
Statement statement = null;
String sql = "";
try {
//获取数据连接
connection = basicUse.getConnection();
//获取发送sql指令执行sql对象
statement = connection.createStatement();
for (int i = 1; i < 10; i++) {
StringBuffer sbf = new StringBuffer("update student set hobby='足球'");
sbf.append(" where id=" + i);
sql = sbf.toString();
System.out.println("执行sql" + sql);
//将指定SQL添加到Statement对象的当前命令列表中
statement.addBatch(sql);
}
//执行成功返回更新计数的数组
int[] success = statement.executeBatch(); //批量执行所有sql返回一个更新计数的数组
return success;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
//执行完数据库操作后记得关闭数据库连接资源
try {
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
批量删除#
public int[] deldBatch() {
Connection connection = null;
Statement statement = null;
String sql = "";
try {
//获取数据连接
connection = basicUse.getConnection();
//获取发送sql指令执行sql对象
statement = connection.createStatement();
for (int i = 1; i < 10; i++) {
StringBuffer sbf = new StringBuffer("delete from student ");
sbf.append(" where id=" + i);
sql = sbf.toString();
System.out.println("执行sql" + sql);
//将指定SQL添加到Statement对象的当前命令列表中
statement.addBatch(sql);
}
//执行成功返回更新计数的数组
int[] success = statement.executeBatch(); //批量执行所有sql返回一个更新计数的数组
return success;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
//执行完数据库操作后记得关闭数据库连接资源
try {
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
完整项目案例
点击这里 github
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端