Home > Database > Mysql Tutorial > 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?

DDD
Release: 2024-12-20 02:30:15
Original
522 people have browsed it

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});
Copy after login

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}]
});
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template