【问题标题】:mysql insert with node.jsmysql 用 node.js 插入
【发布时间】:2013-01-27 02:10:31
【问题描述】:

我正在尝试使用 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();

我对节点很陌生,所以我确定我遗漏了一些明显的东西,但这看起来很简单,我什至无法以明显的方式破坏它——它不会打印任何错误——基本上什么都没有发生。

有什么建议吗?

【问题讨论】:

  • 什么都没发生意味着您甚至没有看到console.dir(client) 行输出?我会尝试在解释器中逐行执行,看看会发生什么

标签: javascript mysql node.js


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 2014-07-21
    • 1970-01-01
    相关资源
    最近更新 更多