2011-11-16 121 views
1

我想在批处理中执行2个sql语句。第一个语句是一个为其ID使用自动生成的值的插入。第二条语句是插入到另一个表,但它需要从上面使用自动生成的值作为插入值的一部分MySQL批处理语句Statement.RETURN_GENERATED_KEYS

像(其中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()和预准备语句。

回答

2

我不确定这是一种方式,你可以用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); 

希望这会有所帮助。

+0

生病请试试看看哪个更快。谢谢 – ducati1212