1

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?

1
  • Nothing happens meaning you don't even see the console.dir(client) line output? I would try executing each line one by one in the interpreter and see what happens Commented Jan 26, 2013 at 17:42

1 Answer 1

2

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();
  });
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.