gpt4 book ai didi

java - 带有 PreparedStatement 的 JDBC 批处理在 MySQL 中不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 11:42:10 26 4
gpt4 key购买 nike

规范:MYSQL 5.7.16、JDK1.7、TOMCAT 8、mysql-connector-java-6.0.4.jar、WINDOWS 10

下面的代码没有将批处理方法更新到数据库

Preparestatement pst = null;
String[] sqlx = {
"insert to abc('col1','col2')values('first', 'data')"
"insert to abc('col1','col2')values('second','data')"
"insert to abc('col1','col2')values('third', 'data')"
};

for(String sqIn : sqlx){
pst = <jdbcConn>.preparestatement(sqIn);
pst.addBatch();
}
int[] chkSql = pst.executeBatch();
//check if chkSql consists of 0..rollback else commit for > 0

在代码的 Debug模式下,chkSql 总是有'1'..这很晕?只有1行插入成功,其他未插入。

这是 MYSQLDB 或 JAR 的错误吗????

最佳答案

看起来您正在创建一个新的 PreparedStatement在每次迭代中,因此 executeBatch() 将仅应用于最后一个 PreparedStatement 对象。

此外,PreparedStatement 用于避免 SQL 注入(inject),当您使用 ? 占位符系统时,它会处理值转义。

addBatch()您使用的方法适用于可变参数:

void addBatch() throws SQLException

Adds a set of parameters to this PreparedStatement object's batch of commands.

,而不是像你尝试做的那样使用原始查询(为此,你将使用 addBatch(java.lang.String query)

void addBatch(String sql) throws SQLException

Adds the given SQL command to the current list of commmands for this Statement object. The commands in this list can be executed as a batch by calling the method executeBatch.

下面的例子应该做你想做的:

String[][] data = { { "first", "data" }, { "second", "data" }, { "third", "data" } };

String sql = "insert into abc(col1,col2) values (?, ?)";// use placeholders

PreparedStatement pst = connection.prepareStatement(sql);// create a single statement

for (String[] row : data) {

// set parameters
pst.setString(1, row[0]);
pst.setString(2, row[1]);

pst.addBatch();// validate the set
}

int[] chkSql = pst.executeBatch(); // execute the batch of commands
//check if chkSql consists of 0..rollback else commit for > 0

关于java - 带有 PreparedStatement 的 JDBC 批处理在 MySQL 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40996436/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com