Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close sql connection when using mysql2/promise?

I have such nodejs code:

var mysql = require('mysql2/promise');

mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "123123",
    database: "mydatabase"
})
.then((connection) => connection.execute("SELECT * FROM mytable"))
.then(([rows, fields]) => {
    console.log(rows);
});

When I execute it, application prints array of database rows and is still running after that. Seems it happens because connection isn't released. How to release it after console.log?

I've tried this way:

var mysql = require('mysql2/promise');

mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "123123",
    database: "mydatabase"
})
.then((connection) => {
    connection.execute("SELECT * FROM mytable")
    .then(([rows, fields]) => {
        console.log(rows);
        connection.release();
    });
});

but result is TypeError: this.connection.release is not a function.

Sorry for my English.

Any ideas?

like image 784
lem0nify Avatar asked Feb 01 '17 18:02

lem0nify


People also ask

How to close connection in mysql Node js?

To close a database connection gracefully, you call the end() method on the connection object. The end() method ensures that all remaining queries are always executed before the database connection closed. To force the connection close immediately, you can use the destroy() method.

How do I close a node JS connection?

If we now: Close our Node server (press CTRL + C at the command line) Start our Node server again by node your-file-name. js.


1 Answers

Since mysql2 mostly keeps API compatibility with mysql, you should be able to close the connection with connection.end().

like image 69
mscdex Avatar answered Oct 05 '22 22:10

mscdex