一个查询中的node-mysql多个语句

我正在使用nodejs 10.26 + express 3.5 + node-mysql 2.1.1 + MySQL-Server Version: 5.6.16

我得到了4 DELETE的,只想要1个数据库请求,所以我连接了DELETE命令的“;”…但总是失败。

 var sql_string = "DELETE FROM user_tables WHERE name = 'Testbase';"; sql_string += "DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase';"; sql_string += "DELETE FROM user_tables_rules WHERE parent_table_name = 'Testbase';"; sql_string += "DELETE FROM user_tables_columns WHERE parent_table_name = 'Testbase';"; connection.query(sql_string, function(err, rows, fields) { if (err) throw err; res.send('true'); }); 

它会抛出这个错误:

 Error: ER_PARSE_ERROR: 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 'DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase';DELETE FR' at line 1 

但是,如果我粘贴这个SQL在PhpMyAdmin它总是成功的…

如果我把它写在单个查询中也是成功的。

  connection.query("DELETE FROM user_tables WHERE name = 'Testbase'", function(err, rows, fields) { if (err) throw err; connection.query("DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase'", function(err, rows, fields) { if (err) throw err; connection.query("DELETE FROM user_tables_rules WHERE parent_table_name = 'Testbase'", function(err, rows, fields) { if (err) throw err; connection.query("DELETE FROM user_tables_columns WHERE parent_table_name = 'Testbase'", function(err, rows, fields) { if (err) throw err; res.send('true'); }); }); }); }); 

感谢帮助!

我猜你正在使用node-mysql 。 文档说:

对于多个语句的支持由于安全原因被禁用(如果值未正确转义,则允许SQL注入攻击)。

多个语句查询

要使用此function,您必须为您的连接启用它:

 var connection = mysql.createConnection({multipleStatements: true}); 

一旦启用,您可以用多个语句执行查询,用分号分隔每个语句; 。 结果将是每个语句的数组。

 connection.query('SELECT ?; SELECT ?', [1, 2], function(err, results) { if (err) throw err; // `results` is an array with one element for every statement in the query: console.log(results[0]); // [{1: 1}] console.log(results[1]); // [{2: 2}] }); 

所以,如果你已经启用了multipleStatements ,你的第一个代码应该可以工作。