Reputation: 166
i'm new at node.js
trying to slect data from mysql with the following ::
con.query('SELECT * FROM country ',function(err,rows){
if(err) throw err;
console.log('Data received from Db:\n');
console.log(rows);
});
i get the Error from jquert-2.1.4-min.js
GET http://localhost:3000/item/create 500 (Internal Server Error)
the connection with data base running ok
/**
* Created by Hussein on 14/01/2016. */
function mysql() {
var mysql = require("mysql");
var con = mysql.createConnection({
host: "127.0.0.1",
port: "3306",
user: "root",
password: "",
database: "mydatabase",
});
con.connect(function (err) {
if (err) {
console.log('Error connecting to Db');
// setTimeout(/*create again */, 2000);
return;
}
console.log('Connection established');
});
con.end(function (err) {
// is some thing must be here
});
con.on('close', function (err) {
if (err) {
// Oops! Unexpected closing of connection, lets reconnect back.
con = mysql.createConnection(connection.config);
} else {
console.log('Connection closed normally.');
}
});
}
module.exports.con = mysql;
Upvotes: 2
Views: 103
Reputation: 2968
the best way to create a DB Connection is
var con = mysql.createConnection({
host : MYSQL_DB_HOST,
user : MYSQL_DB_USER,
password : MYSQL_DB_PWD,
database : MYSQL_DB_NAME
});
con.connect(function(err) {
if(err) {
console.log('con : error when connecting to db : ', err);
setTimeout(/*create again */, 2000);
}
else {
console.log('Connected ');
}
});
con.on('error', function(err) {
console.log('con : db error : ', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') {
//Create Again
}
else {
throw err;
}
});
Can you please verify, you are creating the connection successfully ?
Upvotes: 1