1

I have a script that needs to insert multiple things inside one statement, like

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

the long sql is concatenated based on conditions and needs to be this long. Using this kind of an sql statement in phpmyadmin is valid and inserts it no problem, however JAVA spits out an error.

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 `

Is there something I could do to insert this kind of sql, or should I remake my code to launch several times to achieve the same result?

PaaPs
  • 373
  • 1
  • 4
  • 18

3 Answers3

1

a imple way is using batch SQL insert

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

this is a standard sql weay for insert more rows with an single query

ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
0

Pass only multiple values

See below syntax:

INSERT INTO tbl_name
    (something, something)
VALUES
    (1,2),
    (4,5),
    (7,8);
Devsi Odedra
  • 5,244
  • 1
  • 23
  • 37
-1

you have to split your sql and iterate over it :

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();
}
Logan Wlv
  • 3,274
  • 5
  • 32
  • 54
  • While this may work, it incurs on using more network bandwith since now you're sending 3 different statements to the database rather than 1. – Luiggi Mendoza Jul 20 '18 at 13:30
  • It's true when you're only doing insert into on the same table like in this case, but isn't it a way to do things if you have a sql string like : "insert into tab1 ... ; update tab2 ...; insert into tab3 ... ; "insert into tab4 ..." – Logan Wlv Jul 20 '18 at 13:36
  • Yes: add `allowMultiQueries` parameter in your connection string, as explained in https://mariadb.com/kb/en/library/about-mariadb-connector-j/ – Luiggi Mendoza Jul 20 '18 at 13:42
  • I didn't know about this parameter , thank you for the correction – Logan Wlv Jul 20 '18 at 13:46