I am working on a project using Java + Connector/J + MySQL. I need to execute the following query using one PreparedStatement. Is it possible?
INSERT INTO FILES (FILENAME, FILESIZE, HASH) VALUES (a,b,c)
ON DUPLICATE KEY UPDATE FILEID=LAST_INSERT_ID(FILEID);
INSERT INTO DISTRIBUTES (PEERID, FILEID) VALUES (1,LAST_INSERT_ID());
When I try to execute this, I get an error. I know how to make batch executions of the same INSERT statement, but I can't make it run using multiple inserts in one statement.
The code in java to execute the above, is this:
query = "INSERT INTO FILES (FILENAME, FILESIZE, HASHROOT, HASHLIST) VALUES (?,?,?,?)\n" +
"ON DUPLICATE KEY UPDATE FILEID=LAST_INSERT_ID(FILEID);\n" +
"INSERT INTO DISTRIBUTES (PEERID, FILEID) VALUES (" + peerID + ",LAST_INSERT_ID());";
pstmt = null;
try
{
pstmt = conn.prepareStatement(query);
stmt.setString(1, files[i].getFileName());
pstmt.setLong(2, files[i].getFileSize());
pstmt.setString(3, /* Get some data here */);
pstmt.setBytes(4, /* Get some data here */);
pstmt.addBatch();
pstmt.executeBatch();
}
catch (Exception ex)
{
// Error handling
}
finally
{
// Close resources
}
EDIT: The error I get in the catch block, is saying "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 DISTRIBUTES (PEERID, FILEID) VALUES (16,LAST_INSERT_ID())' at line 3"