Node + Mysql - Issue with connection - javascript

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

Related

Connexion lost after exactly 1 minut / 60 seconds of execution

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;
}
});

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 ?
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

Mysql node.js intermittent connectivity issue

In my node.js app I am using the mysql library for database connectivity.
When I start my node server I can query the database perfectly fine – no issues
When I query the database after 5 minutes the server returns the following error:
{"code":"PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR","fatal":false}
If I restart my node.js server I can query again with no issues…
Here is my code
const mysql = require('mysql');
let connection = mysql.createPool({
host: config.mysql.host,
user: config.mysql.user,
password: config.mysql.password,
database: config.mysql.database
});
router.post('/subscription', (req, res) => {
const user = req.body;
const q = 'INSERT into Subscription SET ?';
connection.query(q, user, (err, results) => {
if (err)
return res.json(err);
return res.json(results);
});
});
I have used both mysql.createConnection and mysql.createPool…. also tried ending the connection manually with connection.end….
Both results end in the same error.
You need to get a connection from the pool and use that, not query the pool itself. When you get a connection from the pool, the pool will make sure you get a valid connection from the pool. So your code would be:
const mysql = require('mysql');
let pool = mysql.createPool({
host: config.mysql.host,
user: config.mysql.user,
password: config.mysql.password,
database: config.mysql.database
});
router.post('/subscription', (req, res) => {
const user = req.body;
const q = 'INSERT into Subscription SET ?';
pool.getConnection(function(err, connection) {
if (err)
return res.json(err);
connection.query(q, user, (err, results) => {
if (err)
return res.json(err);
return res.json(results);
});
})
});
UPDATE:
You don't need to do separate pool.getConnection and connection.query, you can combine them into a pool.query which will get a connection, do the query and release the connection. So, the updated code would be:
const mysql = require('mysql');
let pool = mysql.createPool({
host: config.mysql.host,
user: config.mysql.user,
password: config.mysql.password,
database: config.mysql.database
});
router.post('/subscription', (req, res) => {
const user = req.body;
const q = 'INSERT into Subscription SET ?';
pool.query(q, user, function(err, connection) {
if (err)
return res.json(err);
return res.json(results);
});
});

Node.js MySQL module - throw err; // Rethrow non-MySQL errors;

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);
});

How can i pipe mysql data to a browser window instead of the console in Nodejs?

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");
});

Categories

Resources