我有一个脚本,需要在一个语句中插入多个东西,例如
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);long 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,还是应该重新编写代码以多次启动以实现相同的结果?
发布于 2018-07-20 13:27:10
一种简单的方法是使用批处理SQL插入。
sql = "INSERT INTO `table` (something, something)
VALUES (smth,smth), (smth,smth)";这是一个标准的sql weay,用于使用单个查询插入更多行。
发布于 2018-07-20 13:28:03
只传递多个值
见下面的语法:
INSERT INTO tbl_name
(something, something)
VALUES
(1,2),
(4,5),
(7,8);发布于 2018-07-20 13:29:27
您必须拆分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();
}https://stackoverflow.com/questions/51443555
复制相似问题