Multi-Statement Query Support in Node-MySQL
In Node.js, the question arises when executing multiple SQL statements in a single query using the node-mysql package.
The code provided by the user attempts to delete records from four tables using a semi-colon (;) to separate the statements. However, this results in an error stating that there's an error in the SQL syntax.
The node-mysql documentation originally disabled support for multiple statements for security reasons, as it could lead to SQL injection attacks. To enable this feature, you need to set multipleStatements to true when creating a connection:
var connection = mysql.createConnection({multipleStatements: true});
By doing so, you can execute multiple statements with a semi-colon separator, and the result will be an array with one element for each statement.
Example:
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}] });
In your case, by setting multipleStatements to true, your initial code should successfully execute the four DELETE statements in a single query, eliminating the need for multiple queries and improving code efficiency.
The above is the detailed content of How Can I Execute Multiple SQL Statements in a Single Query Using Node-MySQL?. For more information, please follow other related articles on the PHP Chinese website!