2

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;

1 Answer 1

1

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 ?

Sign up to request clarification or add additional context in comments.

2 Comments

the connection is ok for sure because i get with console.log that message Connected
are you calling con.end or conn.destroy before the result call back hit ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.