带有Statement.RETURN_GENERATED_KEYS的MySQL批处理stmt

我试图批量执行2个SQL语句。 第一个语句是一个插件,它为其ID使用自动生成的值。 第二个语句是对另一个表的插入,但它需要使用上面的自动生成值作为插入值的一部分

类似的东西(其中id只是为了显示自动生成的字段,它没有在sql中定义)

stmt.addbatch(insert into table1("id_auto_generated", "foo")); stmt.addbatch(insert into table2("table1_id", "boo")); 

我现在这样做的方法是在我的第二个sql中使用它

 insert into table2(LAST_INSERT_ID(), "boo"); 

问题是即使在批处理语句中它也很慢,因为我的批处理可以是50,000个插入。

我想切换到预准备语句,但不知道如何将Statement.RETURN_GENERATED_KEYS或LAST_INSERT_ID()与预准备语句一起使用。

我不确定这是否可以通过addBatch执行此操作,除非您使用的方式。 要尝试的另一件事是放弃addBatch()方法并尝试关闭自动提交。 然后你可以使用stmt.getGeneratedKeys(); 。 就像是:

 connection.setAutoCommit(false); stmt.executeUpdate("insert into table1(\"id_auto_generated\", \"foo\") ..."); DatabaseResults results = stmt.getGeneratedKeys(); // extract the id from the results stmt.executeUpdate("insert into table2(\"table1_id\", \"boo\") ..."); ... many more stmts here connection.commit(); connection.setAutoCommit(true); 

希望这可以帮助。