简体   繁体   中英

Running Multiple Queries in Nodejs MySQL

I'm using the mysql library for node.js applications. I'm new to MySQL in general, but I've been able to successfully run a single query and return the data to my webclient. The problem is it only seems to run once (before throwing an error). Here's the code running on my server:

//connect to MySQL server
connection.connect(function(err) {
  if (err) {
    console.error('error connecting: ' + err.stack);
    return;
  }
  console.log('connected as id ' + connection.threadId);
});

//do MySQL query
connection.query('SELECT * FROM `mydatabase` WHERE `tag` = \"' + data.AppID + '\" AND `time` BETWEEN \"' + t_from.toISOString() + '\" AND \"' + t_to.toISOString() + '\" ORDER BY ID DESC', function (error, results, fields) {
  //return the results to webclient here.
});

//close the connection
connection.end();

So, basically every time I click a button, it sends a request to the server (using socket.io) and runs the query. It first creates the connect, runs the query (and returns the data to the webclient), and closes the connection. This works the first time I click the button, but any subsequent clicks returns nothing. My understanding was that I need to open and close the connection every time I run a query (and not leave it open)... but can someone tell me what I'm doing wrong?

Per Kevin and Elmigranto's suggestions... I used a connection pool instead. Here's how I set it up:

//setup MySQL connection parameters
var mysql      = require('mysql');

var pool  = mysql.createPool({
  connectionLimit : 10,
  host     : 'somehost.com',
  user     : 'user',
  password : 'password'
});

Then, inside my function that I use to make the query, I use this:

//do MySQL query
pool.getConnection(function(err, connection) {
  // Use the connection
  connection.query('SELECT * FROM `mydatabase` WHERE `tag` = \"' + data.AppID + '\" AND `time` BETWEEN \"' + t_from.toISOString() + '\" AND \"' + t_to.toISOString() + '\" ORDER BY ID DESC', function (error, results, fields) {
    //return the results to the webclient here
    connection.release();
  });
});

Hope that helps anyone looking for the same answer.

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