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 ?
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
because all the queries must complete before ending a connection put the following line outside the callback:
connection.end();
You can end the process by calling the
process.exit(); method.
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
Related
I have a web server run by node.js
It uses Express, Socket.io, and MySQL
I use socket.io to transmit data from client to server, and also to call queries.
After implementing SQL connexion and queries, the server started to stop after exactly 60 seconds running it.
SQL part in the index.js file:
// SQL
var mysql = require('mysql');
var con = mysql.createConnection({
host: "...",
user: "...",
password: "...",
database: "..."
});
//Socket.io
var io = require('socket.io') (serv, {});
io.sockets.on('connection', function(socket) {
// Select
socket.on("recherche", function(data) {
if (err) throw err;
con.query("SELECT * FROM ..", function (err, result, fields) {
if (err) throw err;
socket.emit("...", {data: result});
});
});
// Insert into
socket.on("...", function(data) {
con.connect(function(err) {
if (err) throw err;
var sql = "INSERT INTO ... VALUES (...)";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
});
});
Everything is working just fine for 60 second after start the server.
Then, I have this error message in the nodejs console:
C:\Users\...>node index.js
events.js:187
throw er; // Unhandled 'error' event
^
...
Error: Connection lost: The server closed the connection.
...
fatal: true,
code: 'PROTOCOL_CONNECTION_LOST'
Thank you in advance to read my question :D
connection = mysql.createConnection(db_config); // Recreate the connection, since
connection.connect(function(err) {
if(err) {
console.log('error when connecting to db:', err);
setTimeout(handleDisconnect, 2000);
}
});
connection.on('error', function(err) {
console.log('db error', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
handleDisconnect();
} else {
throw err;
}
});
I'm trying to use the mysql module to get some data from a mysql database and then write it to an HTML page but it seems stuck inside the query function itself.
The code looks like this:
rooms = [];
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "MYUSERNAME",
password: "MYPASSWORD",
database: "travel"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM rooms", function (err, result, fields) {
if (err) throw err;
var rooms = result;
console.log(rooms[9]);
});
});
console.log(rooms);
The first console.log outputs the results properly, but the second one returns the empty array as declared in the first line and prints first. I'm new to Javascript so I'm probably missing something very obvious. Thanks in advance.
I think you are recreating another variable because adding "var " before. Have you tried without it?
If it doesn't work, here another posible solution:
global.rooms = [];
global.rooms = result;
https://nodejs.org/api/globals.html#globals_global
var rooms = [];
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "MYUSERNAME",
password: "MYPASSWORD",
database: "travel"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM rooms", function (err, result, fields) {
if (err) throw err;
rooms = result;
console.log(rooms[9]);
});
});
console.log(rooms);
you missed out to declare rooms as global variable.
approach using a callback function
rooms = [];
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "MYUSERNAME",
password: "MYPASSWORD",
database: "travel"
});
function query(callback) {
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM rooms", function (err, result, fields) {
if (err) throw err;
var rooms = result;
callback(rooms);
console.log(rooms[9]);
});
});
}
function log_it_out() {
console.log(rooms);
}
query(log_it_out);
I don't think it matters for you anymore since it's been roughly a year since you asked this basic question, however maybe someone else that searches for this question might find this information helpful since I had the same problem.
**} else if(req.url === "/api/labeat") {
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(information));**
IMPORTANT
When you try to return something to a website beside the variable declarations, when you use res.end();, make sure to turn the result or whatever kind of information you're trying to work with into a string or buffer since the res.end() expects either a string or a buffer. Also specify the Content-Type as I did (application/json).
today I tried node.js mysql snippet from w3schools:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "roots", // WRONG USER
password: ""
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
/*Create a database named "mydb":*/
con.query("CREATE DATABASE mydb", function (err, result) {
if (err) throw err;
console.log("Database created");
});
});
I wanted to learn how to handle mysql errors, because my app require mysql. But after I started app.js file this error showed up:
Why can't I throw an error?
I wanted to learn how to handle mysql errors, because my app require
mysql.
MySQLJS Error handling
To catch the errors you throw, try with the following snippet :
con.on('error', function(err) {
console.log("[mysql error]",err);
});
change you're database conn like this
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret',
database : 'secret'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
I do some mistake with connecting mysql in express which i couldn't figure out.
The basic connection code below works well.
var connection = mysql.createConnection({
host : 'localhost',
user:'root',
password:'',
database :'testdb'
});
connection.connect();
connection.query('SELECT * from test2table', function (err, data) {
if (err) throw err
console.log('The solution is: '+JSON.stringify(data)); -->could obtain data
});
But when it comes to use inside a get/post method , i donot get a response. Like code below:
var connection = mysql.createConnection({
host : 'localhost',
user:'root',
password:'',
database :'testdb'
});
connection.connect(function(err){
if(err) throw err;
console.log("connected");
});
app.get('/api/records',function(req,res){
connection.query('SELECT * from test2table', function (err, data) {
console.log(data);--> get blank response
});
});
Please let me know if i missed anything inbetween which affects. Thankyou.
Can you try with app.locals?
var connection = mysql.createConnection({
host : 'localhost',
user:'root',
password:'',
database :'testdb'
});
connection.connect(function(err){
if(err) throw err;
console.log("connected");
});
app.locals.connection = connection;
app.get('/api/records',function(req,res){
app.locals.connection.query('SELECT * from test2table', function (err, data) {
console.log(data);--> get blank response
});
});
See more details here: http://expressjs.com/en/api.html#app.locals
Hi I am currently trying to output mysql data to a browser window instead of the console, and I have not a clue on how to do this in Node, which I am quite new to.
Here is the mysql.js file:
'
var mysql = require ("mysql");
var connection = mysql.createConnection({
host:"localhost",
user: "root",
});
connection.connect(function (err) {console.log( "Successfully Connected.");
if (err) throw err;
});
var query = connection.query("SELECT * FROM myTable", function (err, result, fields){
if (err) throw err;
console.log('result:', result);
});
connection.end();'
You need to create a server which you can connect to and receive data from with a browser. The most convenient and by far the simplest way to do this is HTTP. You can read about HTTP servers in node.js here. The fist code snippet on that page demonstrates a HTTP server with one handler function, which is all you need to achieve your goal.
An (untested) example for convenience:
// Dependencies
var mysql = require("mysql"),
http = require("http");
// This holds our query results
var results;
// Connect to database
var connection = mysql.createConnection({
host: "localhost",
user: "root"
});
connection.connect(function(err) {
if (err) throw err;
console.log("Connected to database");
});
connection.query("SELECT * FROM myTable", function(err, rows, fields) {
if (err) throw err;
results = rows;
connection.end(); // Disconnect from database
});
// Function to handle browser's requests
function requestHandler(req, res) {
res.end(JSON.stringify(results)); // Respond to request with a string
}
// Create a server
var server = http.createServer(requestHandler);
// That magic number 8080 over here is the port our server listens to.
// You can access this webpage by visiting address http://localhost:8080
server.listen(8080, function() {
console.log("Server online");
});