Joe
Joe

Reputation: 13091

Java script - how to end connection to DB?

I have a code bellow and it is running fine (getting data from database) but when I run it from a terminal (e.g. node db.js) - it gives data back but never closes (can not type next command in terminal.

var mysql = require('mysql');

var connection = mysql.createConnection({
    host: '...',
    user: '...',
    password: "...,
    port : ..., //port mysql
    database: '...'
});

connection.connect(function(err) {
  if (err) throw err;
  connection.query("SELECT * FROM table", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
  });
});

What should be added to the end of .js ?

Upvotes: 0

Views: 207

Answers (4)

Hackinet
Hackinet

Reputation: 3328

You can end connections with connection.end(); You must add it after the query because the query must be completed first. Here is your modified code:

var mysql = require('mysql');

var connection = mysql.createConnection({
    host: '...',
    user: '...',
    password: "...,
    port : ..., //port mysql
    database: '...'
});

connection.connect(function(err) {
  if (err) throw err;
  connection.query("SELECT * FROM table", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
  });
  connection.end();
});

Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.

https://github.com/mysqljs/mysql#introduction

Upvotes: 1

Jpec07
Jpec07

Reputation: 858

You need to tell MySQL.js to close the connection, once you're done with the query. For example:

var mysql = require('mysql');

var connection = mysql.createConnection({
    host: '...',
    user: '...',
    password: "...,
    port : ..., //port mysql
    database: '...'
});

connection.connect(function(err) {
  if (err) throw err;
  connection.query("SELECT * FROM table", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
    connection.end(function (err) { if (err) throw err; } });
  });
});

For more info, see MySQL.js docs: https://github.com/mysqljs/mysql#terminating-connections

Upvotes: 0

user7896971
user7896971

Reputation:

You can end the process by calling the process.exit(); method.

Upvotes: 0

Landa
Landa

Reputation: 34

because all the queries must complete before ending a connection put the following line outside the callback:

connection.end();

Upvotes: 0

Related Questions