nodejs-database connection
I work with sockets, use sicket.io, express, node.js and still need to connect mysql. Downloaded the mysql plugin via npm.
I connected everything to the page, this is how it all looks:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "admin",
password: "admin123",
database: "admin"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM users WHERE id = '1'", function (err, result) {
if (err) throw err;
console.log(result);
});
});
The request is successful, from the user's database shows me. But after 10-25 seconds, the server shuts down and gets out this error:
events.js:183
throw er; // Unhandled 'error' event
^
Error: Connection lost: The server closed the connection.
at Protocol.end (/home/admin/web/ssd1.had.yt/public_html/node_modules/mysql/lib/protocol/Protocol.js:112:13)
at Socket.<anonymous> (/home/admin/web/ssd1.had.yt/public_html/node_modules/mysql/lib/Connection.js:94:28)
at Socket.<anonymous> (/home/admin/web/ssd1.had.yt/public_html/node_modules/mysql/lib/Connection.js:526:10)
at emitNone (events.js:111:20)
at Socket.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:139:11)
at process._tickCallback (internal/process/next_tick.js:181:9)
I was looking for a solution on the Internet, I realized that the connection to the database should be closed.
I added this one line:
con.end();
And now when closing the connection to the database, the server turns off, tell me, maybe there is some option?
1 answers
Hello again, I figured out my problem. The following helped me:
-
I have connected the mysql2 module It is downloaded like this:
npm install --save mysql2
-
I perform the connection using the pool plugin Like this:
const pool = mysql.createPool({
host: 'localhost',
user: 'admin',
database: 'admin',
password: 'admin123!',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
And the actual request itself:
$id_db = data.id_bd;
pool.query('SELECT * FROM users WHERE id = ' +$id_db, function(err, rows) {
console.log(rows);
pool.end();
})
This method suited me both for the database version 5.7 and 8+