mysql插入与node.js

我正在尝试使用node.js,并使用node-mysql来处理连接。

到目前为止,我正在从github页面的基本使用,但由于某种原因,我甚至不能得到最简单的连接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(); 

我对节点非常陌生,所以我确信我错过了一些明显的东西,但是这看起来很简单,我甚至不能明显地打破这个东西 – 它不打印任何错误 – 基本上什么也没有发生。

有什么build议?

节点是asynchronous的,所以它不会线性地执行它的动作。 通过做这个:

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

您正在开始初始连接过程,然后在有时间连接之前立即closures客户端连接。 你需要asynchronous执行你的任务。

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