我想一次删除三个不同的表,我已经创建了一个非常简单的SQL语句,如下所示:
DELETE FROM tbl1;DELETE FROM tbl2;DELETE FROM tbl3;
当我直接在mysql中运行但是来自java no!
时,这个语句是正确的我的java代码:
public boolean clearTables()
{
boolean ans = false;
if (con != null)
{
try
{
String deleteQuery = " DELETE FROM tbl1;DELETE FROM tbl2;DELETE FROM tbl3;";
Statement st = con.createStatement();
st.execute(deleteQuery);
ans = true;
}
catch (Exception e)
{
e.printStackTrace();
ans= false;
}
}
return ans;
}
如何在java中一次运行多个SQL语句?
答案 0 :(得分:8)
使用addBatch
然后executeBatch
:
Statement st = con.createStatement();
st.addBatch("DELETE FROM tbl1");
st.addBatch("DELETE FROM tbl2");
st.addBatch("DELETE FROM tbl3");
int[] results = st.executeBatch();
然后results
将包含一个数组,其中包含从每个表中删除的行数。
答案 1 :(得分:2)