0

I have a basic Twitter-like app which works fine when one user is online. However, when more than one user comes online and tries to perform an SQL query the server crashes.

This is happening because the function closes the database for the first user while the second user is still mid-function, then the second user tries to close the already closed database, leading to a crash.

Here's a basic function as an example:

function showAllUsers(req, res){
  dbConnect();
  var query = 'SELECT * FROM USERS';
  connection.query(query, function (err,rows,fields){
    if (err) {
        throw err;
    }
    dbClose(req,res);
    console.log(rows);
    res.render('allUsers', { user: req.user, message: req.flash('info'), users: rows })
  })
}

I'm using the mysql package from npm, but I'm assuming I'm not using it correctly. I'm currently opening the database before each query and closing it immediately afterwards.

Is there a safer way to do this, or can I just leave it open until the server quits?

2
  • 2
    Have you taken a look at connection pools? Commented Mar 12, 2013 at 11:58
  • That your code is not working as you expect comes as no surprise. You can't share a connection like this, and it's silly to try. That it is "crashing the server" implies that there are bugs in the code - even though it's a silly use-case, node.js should not respond by crashing. Get a core dump and backtrace and log it as a defect. Commented Mar 12, 2013 at 13:04

1 Answer 1

1

Using connection pools solved this issue for me.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.