Prachi g
Prachi g

Reputation: 839

Terminating a callback in nodejs

I am very new to nodejs. I am using mysql node module. This is how I use it:

var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'sample'
});

connection.connect(function (err) {
    if (!err) {
        console.log("Database is connected ... \n\n");
    } else {
        console.log("Error connecting database ... \n\n");
    }
});

var post  = {PersonID: 1, Name: 'Prachi', City: 'Blore'};
var query = connection.query('INSERT INTO Persons SET ?', post, function(error, result) {
    if (error) {
        console.log(error.message);
    } else {
        console.log('success');
    }
});
console.log(query.sql);

This node code works functionally. As in, it adds data to the table. But it doesn't terminate. What is the mistake which I am making?

Upvotes: 1

Views: 53

Answers (2)

user3334774
user3334774

Reputation: 36

Take a closer look at the official documentation, you have to close the connection :

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'me',
  password : 'secret'
});

connection.connect();

connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
  if (err) throw err;

  console.log('The solution is: ', rows[0].solution);
});

connection.end();

Upvotes: 2

Yuri Zarubin
Yuri Zarubin

Reputation: 11677

Use connection.end() to close the connection

var query = connection.query('INSERT INTO Persons SET ?', post, function(error, result) {
    connection.end();
    if (error) {
        console.log(error.message);
    } else {
        console.log('success');
    }
});

Upvotes: 2

Related Questions