How to query with node-mysql and write out the results?

I am trying to connect to a db on my hosting and write out the result, I am not getting any error, just blank space. line like console.log('test'); put at any place always work but I am not getting any query results, what am I doing wrong?

var mysql      = require('mysql');
var connection = mysql.createConnection({
    host     : 'wm51.wedos.net',
    user     : 'xxxxxx',
    password : 'xxxxxx',
    database: 'd57283_vs'
});

connection.connect();
var queryString = 'SELECT * FROM versus LIMIT 5';

connection.query(queryString, function(err, rows, fields) {
    if (err) throw err;
    for (var i in rows) {
        console.log(rows[i].title); 

    }
});

connection.end();

(The table is called versus, has columns title, url...in adminer it's all accessible and the query works...)

Answers


Be careful with that connection.end(); call at the bottom. NodeJS is asynchronous, remember?

Try putting that at the end of the inner function after the for-loop, otherwise it will get called as soon as the query is called, possibly killing the connection you're trying to use!


perhaps mysql-server is not to be connected, when you query,or mysql-server is to be closed when you query.

var mysql      = require('mysql');
var connection = mysql.createConnection({
    host     : 'wm51.wedos.net',
    user     : 'xxxxxx',
    password : 'xxxxxx',
    database: 'd57283_vs'
});

connection.connect();
process.nextTick(function() {
    var queryString = 'SELECT * FROM versus LIMIT 5';

    connection.query(queryString, function(err, rows, fields) {
        connection.end();
        if (err) throw err;
        for (var i in rows) {
            console.log(rows[i].title); 

        }
});

});

I believe the connection.end() statement still needs to be after the for loop. Or else your ending the connection before the loop even starts.


Need Your Help

Google Analytics: hits stop getting counted

google-analytics

We're implementing Google Analytics in retail consumer kiosk software. There is no Javascript or SDKs or web pages involved - we craft a URL per Measurement Protocol and post it. We find that somet...