[英]execute multiple inserts with PreparedStatement - Java
I am working on a project using Java + Connector/J + MySQL. 我正在使用Java + Connector / J + MySQL进行项目。 I need to execute the following query using one PreparedStatement. 我需要使用一个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. 我知道如何对同一条INSERT语句进行批量执行,但是我无法在一个语句中使用多个插入来使其运行。
The code in java to execute the above, is this: java中执行上述代码的代码是这样的:
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" 编辑:我在catch块中得到的错误是:“您的SQL语法有错误;请查看与您的MySQL服务器版本相对应的手册,以获取在'INSERT INTO DISTRIBUTES(PEERID,FILEID)VALUES附近使用正确的语法(16,LAST_INSERT_ID())'在第3行“
You can only execute one statement with single preparedStatement. 您只能使用单个prepareStatement执行一条语句。 You have to split the sql into two separate insert into
... sequences. 您必须将sql分成两个单独的insert into
...序列。
Also 也
INSERT INTO DISTRIBUTES (PEERID, FILEID) VALUES (" + peerID + ",LAST_INSERT_ID());";
does not look like using a preparedStatment - it has hardcoded peerID
instead of placeholder ?
看起来不像使用peerID
它具有硬编码的peerID
而不是占位符?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.