1

node.jsを試してみて、node-mysqlを使用して接続を処理しています。

これまでのところ、githubページから基本的な使用法に従っていますが、何らかの理由で、機能するための最も単純な接続すら取得できません。

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();

私はノードに非常に慣れていないので、明らかな何かが欠けていると確信していますが、これは非常に簡単なようで、明白な方法で物事を壊すことさえできません-それはエラーを出力しません-基本的に何も起こりません。

何かアドバイス?

4

1 に答える 1

2

ノードは非同期であるため、アクションを直線的に実行しません。これを行うことによって:

client.connect //...
client.end // ...

最初の接続プロセスを開始し、接続する時間がなくなる前に、クライアント接続をすぐに閉じます。タスクを非同期で実行する必要があります。

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();
  });
});
于 2013-01-26T17:43:30.533 に答える