"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > 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?

2025-03-28에 게시되었습니다
검색:216

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.

최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3