"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Execute Multiple SQL Statements in a Single Query Using Node-MySQL?

How Can I Execute Multiple SQL Statements in a Single Query Using Node-MySQL?

Posted on 2025-03-25
Browse:300

How Can I Execute Multiple SQL Statements in a Single Query Using Node-MySQL?

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3