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
- var mysql = require('mysql');
- var connection = mysql.createConnection({
- host: 'localhost',
- user: 'root',
- password: '',
- database: 'anonystick',
- debug: false,
- multipleStatements: true
- });
- connection.connect();
- var sql = "SELECT * FROM trn_employee WHERE employee_id = ?;SELECT * FROM trn_person WHERE person_id = ?";
- connection.query(sql, [2, 1], function(error, results, fields) {
- if (error) {
- throw error;
- }
- console.log(results[0]);
- console.log(results[1]);
- });
- connection.end();
output
- [ { employee_id: 2, first_name: 'Dinesh', last_name: 'Patil' } ]
- [ { person_id: 1, first_name: 'Yashwant', last_name: 'Chavan', age: 10 } ]
Ref: https://www.technicalkeeda.com/nodejs-tutorials/nodejs-mysql-multiple-statement-queries