简体   繁体   中英

nodeJS mysql library how to serially execute query

Say for example if I have code like below would it execute serially or parallely?

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'me',
  password : 'secret',
  database : 'my_db'
});

connection.connect();

let transaction = 'START TRANSACTION; //DO SOMETHING COMMIT;'

connection.query(transaction, function (error, results, fields) {
  if (error) throw error;
  console.log(results);
});

connection.query(transaction, function (error, results, fields) {
  if (error) throw error;
  console.log(results);
});

connection.end();

It does say

The MySQL protocol is sequential, this means that you need multiple connections to execute queries in parallel. You can use a Pool to manage connections, one simple approach is to create one connection per incoming http request.

On the website but I am wondering if 'sequential' means the queries are sent to the database sequentially but executed 'parallely' or if it means whether the next query is never sent until the first query is fully executed (which is what I mean by serial).

If they are being 'executed' parallely in the database, how can I make sure that each query is served as an individual transaction ? I am asking because I have to treat multiple queries (potentially simultaneously requested to server) to be executed serially in the database. Of course this is possible under multiple connections (multiple connection to mysql server with different terminal instance) but how can I simulate that environment using this mysql nodejs library?

I can't use promises or callbacks because I do not know how many or when the queries will be executed. I will only be able to call connection.query every time query is made from the client to the server.

You can leverage javascript promise to solve your problem. You can check https://github.com/tuhinpaul/syp-model/wiki/Programmatic-(Dynamic)-Chaining-and-Recursive-Functions-with-JavaScript-or-Node.js-Promises to understand how to serially execute tasks.

The syp-model package provides the ability to execute queries sequentially although documentation needs more work at this time; and it does not have integrated transaction support yet.

Was it helpful?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM