Home > Database > Mysql Tutorial > How to Execute Multiple SQL Statements in a Single Query with Node-MySQL?

How to Execute Multiple SQL Statements in a Single Query with Node-MySQL?

Patricia Arquette
Release: 2024-12-12 21:21:18
Original
346 people have browsed it

How to Execute Multiple SQL Statements in a Single Query with Node-MySQL?

Multiple Statement Queries in Node-MySQL

In node-mysql, multiple SQL statements can be executed in a single query by connecting them with semicolons (;). However, this feature is disabled by default for security reasons. To enable it, set multipleStatements: true in the connection options.

To use multiple statement queries, construct a SQL string with the statements separated by semicolons. For example:

var sql_string = "DELETE FROM user_tables WHERE name = 'Testbase';"
                + "DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase';"
                + "DELETE FROM user_tables_rules WHERE parent_table_name = 'Testbase';"
                + "DELETE FROM user_tables_columns WHERE parent_table_name = 'Testbase';";
Copy after login

Then, execute the query using connection.query(sql_string, callback). The callback function will receive an error object (if any) and an array of result sets for each statement.

Example:

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

connection.query(sql_string, function(err, results) {
  if (err) throw err;
  
  // results is an array containing the results of each statement
  res.send('true');
});
Copy after login

Note that you may encounter an error if the SQL server version is too old or the database driver is not configured correctly. In such cases, it is recommended to execute the statements individually.

The above is the detailed content of How to Execute Multiple SQL Statements in a Single Query with 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template