java mysql 批量insert,Java - 如何批量数据库插入和更新

这篇博客探讨了如何在Java中使用PreparedStatement进行多种类型的数据库操作,如插入和更新。由于Java不支持在预编译语句中仅使用问号作为占位符,你需要为每种操作创建不同的PreparedStatement对象。在循环中,根据条件决定调用哪个PreparedStatement来添加批处理。先执行更新操作确保数据正确性,然后执行插入操作,以处理依赖于更新的插入情况。

I want to batch up multiple types of database calls in one PreparedStatement. Is this possible?

Is there anyway to do something like

PreparedStatement pstmt = connection.prepareStatement("?");

where the ? can either be INSERT INTO MY_TABLE VALUES(1,2,3,4) or it could be UPDATE MY_TABLE, SET MY_VAL='1' WHERE MY_VAL IS NULL

Or do I always need to specify a table and action for my prepared statement?

解决方案

Java will not allow you add only ? in preparedstatement string parameter, as it expects the ? for the place holder only for the parameters to the give SQL.

For your case, you may have to have 2 prepared statement objects, and in loop through, you can make a decision which one to call. So it would be something like below:

PreparedStatement insertPstmt = connection.prepareStatement("INSERT INTO MY_TABLE VALUES(?,?,?,?)");

PreparedStatement updatePstmt = connection.prepareStatement("UPDATE MY_TABLE, SET MY_VAL=? WHERE MY_VAL IS NULL");

While () {

If () {

// use insert pstmt and add batch

} else {

// use update pstmt and add batch

}

}

insertPstmt.executeBatch();

updatePstmt.executeBatch();

if you have any insert , which has dependency on the update, you might execute the batches accordingly. This will make sure that the update will work correctly. I would think of executing insert first, as they might not depend on update.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值