1

Im working on a register system and i want to check the users username if it already exists in the database while he is typing, so for every letter he types in the input field, i want to do a query to the database.

Currently I have this: on app.js i have this part of the code:

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

app.use(function(req,res,next){
   req.connection = connection;
   next();
});
module.exports = app;

So far I understand this: Whenever a user requests a page, we connect to the server. But do we open a new connection or do we use the same one as before???

Then on the html page i send a request to index.js everytime the user types something into the input field and i do the following on index.js:

 var express = require('express');
 var router = express.Router();

 router.get('/', function(req, res) {
     var val=req.query.parameter;
     var query=req.connection.query("select * from registeredusers where username="+req.connection.escape(val),function(err,result){       
         console.log(query.sql);  
      });

Am I using the same connection here when querying to the database or am I establishing a new connection whenever a user types something into the input field?

EDIT: The connection wasnt persisted, i followed the advice of Mjh, so the sollution for this problem is using pooling connections.Check this links out if you want to know more: When use poolConnection or CreateConnection felixge/node-mysql

node.js + mysql connection pooling

https://codeforgeek.com/2015/03/real-time-app-socket-io/

Community
  • 1
  • 1
xmisd
  • 390
  • 6
  • 17
  • I must admit that I have no idea whether the connection is persistent or not - If I had to guess, I'd say it isn't persistent and that you are constantly opening a new one. To actually *verify*, you can issue a query @ your MySQL stating: `SHOW PROCESSLIST;`. It will show you the actual socket connections. If you keep "hitting" your `node.js` app and if it always reconnects - then process list would show different `id` every time you queried it. Basically, query MySQL, then `SHOW PROCESSLIST`, then query again and issue `SHOW PROCESSLIST again` - compare the values and check if ids differ. – Mjh Jan 25 '16 at 12:41
  • However, I can see that the `mysql` package features pooling connections. It would appear that's what you're after. – Mjh Jan 25 '16 at 12:41
  • YES you are right thank you my friend, the connection wasnt persistened and I've searched for pooling connections and i know what i must do now. Thank you for your answer!!! – xmisd Jan 25 '16 at 12:45
  • No problem, I'm glad I helped! Good luck and have a nice day! :) – Mjh Jan 25 '16 at 12:47

0 Answers0