title: Node.js server crashes after MySQL connection ends
body: <p>I have a Node.js server that is hosting my webpage. I have recently set up a MySQL server and created a connection to the server. When accessing a certain page, it queries the SQL database.</p>
  
  <p>My problem is that if I query the DB, it makes the connection just fine, but it will crash a little later when the server automatically closes the connection. I then tried to use con.end() after the query, but this crashes the second I access the DB. It throws the error below:</p>
  
  <pre><code>    at Protocol._validateEnqueue (/home/pi/Documents/node_modules/mysql/lib/protocol/Protocol.js:203:16)
      at Protocol._enqueue (/home/pi/Documents/node_modules/mysql/lib/protocol/Protocol.js:138:13)
      at Connection.query (/home/pi/Documents/node_modules/mysql/lib/Connection.js:200:25)
      at Handshake.con.connect (/home/pi/Documents/PageDB.js:26:9)
      at Handshake.&lt;anonymous&gt; (/home/pi/Documents/node_modules/mysql/lib/Connection.js:502:10)
      at Handshake._callback (/home/pi/Documents/node_modules/mysql/lib/Connection.js:468:16)
      at Handshake.Sequence.end (/home/pi/Documents/node_modules/mysql/lib/protocol/sequences/Sequence.js:83:24)
      at Handshake.Sequence.OkPacket (/home/pi/Documents/node_modules/mysql/lib/protocol/sequences/Sequence.js:92:8)
      at Protocol._parsePacket (/home/pi/Documents/node_modules/mysql/lib/protocol/Protocol.js:278:23)
      at Parser.write (/home/pi/Documents/node_modules/mysql/lib/protocol/Parser.js:76:12) code: 'PROTOCOL_ENQUEUE_AFTER_QUIT', fatal: false }
  Close the database connection.
  </code></pre>
  
  <p>It seems to me that this is caused by the query executing after the con.end() runs. Can someone help me figure out a way to call the end function after the callback has returned with the SQL query data? Or otherwise, have my web server not crash when the connection to the DB is closed automatically? I'm open to either one. Thanks!</p>
  
  <p>Code for the Node.js server is below:</p>
  
  <pre><code>//Create a connection to the db
  const con = mysql.createConnection({
    host: 'localhost',
    user: 'test',
    password: 'test',
    database: 'test',
  });
  
  router.get('/products',(req,res)=&gt;{
    con.connect((err) =&gt; {
      if(err){
        console.log('Error relating to connection: ' + err);
        return;
      }
      console.log('Connection established');
  
      con.query('SELECT * FROM ProductList',(err,rows,fields)=&gt;{
        if(!err)
          res.send(rows);
        else
          console.log(err);
      })
    });
    con.end(function(err) {
    if (err) {
      return console.log('error:' + err.message);
    }
    console.log('Close the database connection.');
    });
  });
  </code></pre>