Node.js MySQL Multiple Statement Queries

Nội dung bài viết

Video học lập trình mỗi ngày

In this tutorial, You will learn how to execute multiple sql queries using node.js and mysql. To execute multiple SQL statements you need enable multipleStatements option. by default multiple statements is disabled for security reasons.

  • require('mysql') - Load the mysql module to connect to database.
  • Define mysql connection details like host, user, password and database.
  • Establish database connection with mysql using connection.connect() function.
  • To execute multiple SQL statements you need enable multipleStatements: true option while obtaining connection, In this example we will fetch records from "trn_employee" and "trn_person" tables.
  • results[0] - represents result of first sql statement and results[1] result of second sql statement.
  • connection.end() - close the database connection.

Multiple statement queries

  1. var mysql = require('mysql');
  2.  
  3. var connection = mysql.createConnection({
  4. host: 'localhost',
  5. user: 'root',
  6. password: '',
  7. database: 'anonystick',
  8. debug: false,
  9. multipleStatements: true
  10. });
  11. connection.connect();
  12.  
  13. var sql = "SELECT * FROM trn_employee WHERE employee_id = ?;SELECT * FROM trn_person WHERE person_id = ?";
  14.  
  15. connection.query(sql, [2, 1], function(error, results, fields) {
  16. if (error) {
  17. throw error;
  18. }
  19. console.log(results[0]);
  20. console.log(results[1]);
  21. });
  22.  
  23. connection.end();

output

  1. [ { employee_id: 2, first_name: 'Dinesh', last_name: 'Patil' } ]
  2. [ { person_id: 1, first_name: 'Yashwant', last_name: 'Chavan', age: 10 } ]

Ref: https://www.technicalkeeda.com/nodejs-tutorials/nodejs-mysql-multiple-statement-queries

Có thể bạn đã bị missing