[英]How to insert into two different tables in one statement with Java and MySQL?
我正在使用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模板進行組合時會出現問題。
謝謝!
使用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();
對於任何想要使用MySQL從jdbcTemplate執行多個語句而不使用批量更新的人:
在url的末尾添加“?allowMultiQueries = true”(參見下面的示例)。
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/tt?allowMultiQueries=true" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
使用jdbcTemplate.execute方法,Spring 3.0.2和MySQL驅動程序v5.1.9進行測試
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
MySQL JDBC驅動程序不支持由';'分隔的多個語句,即使MySQL客戶端本身也是如此。 如果必須使用Java,則不能依賴於此。
如果你有100K記錄,你確定Java是適合這項工作的工具嗎? 我想知道如果這是一個批處理作業,MySQL導入工具或ETL會更好。
另外,Spring批處理模塊怎么樣? 它有什么特別針對這個問題的嗎?
您需要單獨執行每個語句。 首先,插入table1,然后插入table2
你錯過了分號了嗎? 在第二個聲明中。 我認為這是一個語法錯誤而不是其他任何東西。
嘗試在mysql控制台上運行兩個命令,如果語法正確則se。
我總是在控制台上運行coomand以確保sytax。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.