如何使用Java和MySQL在一个语句中插入两个不同的表?

Mal*_*ker 5 java mysql spring

我正在使用Java,Spring(NamedParameterJdbcTemplate)和MySQL.我的陈述如下:

INSERT INTO Table1 (Name) VALUES (?);
INSERT INTO Table2 (Path, Table1Id) VALUES (?, LAST_INSERT_ID())

但它抛出以下错误:

PreparedStatementCallback; bad SQL grammar [INSERT INTO Table1 (Name) VALUES (?);
INSERT INTO Table2 (Path, Table1Id) VALUES (?, LAST_INSERT_ID())]`

嵌套异常是:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO Table2 (Path, Table1Id' at line 1

这种语法在MySQL中运行良好,但是在通过Spring模板进行组合时会出现问题.

谢谢!

mar*_*igo 5

使用addBatch方法运行多个语句


Statement stmt = con.createStatement();
   stmt.addBatch(
    "update registration set balance=balance-5.00
        where theuser="+theuser);
   stmt.addBatch(
    "insert into auctionitems(
                   description, startprice) 
        values("+description+","+startprice+")");

   int[] results = stmt.executeBatch();

资源


a1e*_*x07 0

您需要单独执行每条语句。首先插入table1,然后插入table2