Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert into two different tables in one statement with Java and MySQL?

Tags:

java

mysql

spring

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!

like image 707
MalcomTucker Avatar asked Mar 12 '10 00:03

MalcomTucker


2 Answers

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

source

like image 186
marcosbeirigo Avatar answered Sep 27 '22 23:09

marcosbeirigo


For anyone who wants to execute multiple statements from jdbcTemplate with MySQL without using batch update:

Add "?allowMultiQueries=true" at the end of the url (see example below).

<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>

Tested with jdbcTemplate.execute method, Spring 3.0.2 and MySQL driver v5.1.9

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.9</version>
    </dependency>
like image 26
tomasz.koscinski Avatar answered Sep 28 '22 00:09

tomasz.koscinski