串联sql语句插入

时间:2018-07-20 13:24:27

标签: java mysql sql jdbc mariadb

我有一个脚本,需要在一个语句中插入多个内容,例如

sql = "INSERT INTO `table` (something, something) VALUES (smth,smth); INSERT INTO `table` (something, something) VALUES (smth,smth)";
Statement stmt = connection_db.createStatement();  
 boolean update = stmt.execute(sql);

长条sql是根据条件并置的,因此必须很长。在phpmyadmin中使用这种sql语句是有效的并且可以毫无问题地插入它,但是JAVA吐出了一个错误。

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INSERT INTO `

是否可以做一些插入这种sql的操作,还是应该重新编写代码以多次启动以达到相同的结果?

3 个答案:

答案 0 :(得分:1)

一种简单的方法是使用批处理SQL插入

  sql = "INSERT INTO `table` (something, something) 
          VALUES (smth,smth), (smth,smth)";

这是标准的sql方法,可通过单个查询插入更多行

答案 1 :(得分:0)

仅传递多个值

请参见以下语法:

INSERT INTO tbl_name
    (something, something)
VALUES
    (1,2),
    (4,5),
    (7,8);

答案 2 :(得分:-1)

您必须拆分sql并对其进行迭代:

sql = "INSERT INTO `table` (something, something) VALUES (smth,smth); INSERT INTO `table` (something, something) VALUES (smth,smth)";
sqls = sql.split(";");
for(int i=0; i<sqls.length;sqls++) {
  statement = connection.prepareStatement(sqls[i]);
  statement.execute();
}