900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > java mysql连接两张表 如何使用Java和MySQL在一个语句中插入两个不同的表?

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

时间:2022-01-31 18:03:31

相关推荐

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

I am using Java, Spring (NamedParameterJdbcTemplate) and MySQL. My statement looks like this:

INSERT INTO Table1 (Name) VALUES (?);

INSERT INTO Table2 (Path, Table1Id) VALUES (?, LAST_INSERT_ID())

But it is throwing the following error:

PreparedStatementCallback; bad SQL grammar [INSERT INTO Table1 (Name) VALUES (?);

INSERT INTO Table2 (Path, Table1Id) VALUES (?, LAST_INSERT_ID())] `

Nested exception is:

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

The syntax works fine in MySQL but something is up when combining via the Spring template.

Thanks!

解决方案

Use the addBatch method to run multiple statements

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();

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。