Reputation: 10422
I'm having a try with node.js, and am using node-mysql to handle the connections.
So far I'm following the basic usage from the github page, but for some reason I can't even get the most simple connection to function.
var mysql = require('mysql');
var db_host = 'localhost';
var db_user = 'root';
var db_pass = 'pass';
var db_name = 'mydb';
var client = mysql.createConnection({
host: db_host,
user: db_user,
password: db_pass,
database: db_name
});
console.dir(client); // prints a whole bunch of connection object data
client.connect(function(err) {
// connected! (unless `err` is set)
console.dir('got here!'); // prints nothing!
if (err) console.dir(err); // prints nothing!
});
client.query('SELECT 1', function(err, rows) {
console.log('here'); // print nothing!
console.dir(err); // prints nothing!
console.dir(rows); // prints nothing!
});
client.end();
process.exit();
I'm very new to node so I'm sure I'm missing something obvious, but this seems pretty straightforward and I can't even get the thing to break in an obvious way-- it prints no errors-- basically nothing happens.
Any advice?
Upvotes: 1
Views: 828
Reputation: 161447
Node is asynchronous, so it will not perform its actions linearly. By doing this:
client.connect //...
client.end // ...
You are starting the initial connection process and then immediately closing your client connection, before it has had time to connect. You need to perform your tasks asynchronously.
client.connect(function(err) {
// connected! (unless `err` is set)
console.dir('got here!'); // prints nothing!
if (err)console.dir(err); // prints nothing!
client.query('SELECT 1', function(err, rows) {
console.log('here'); // print nothing!
console.dir(err); // prints nothing!
console.dir(rows); // prints nothing!
client.end();
process.exit();
});
});
Upvotes: 2