nodejs 与 mysql联接

首先安装Mysql 模块吧

npm install mysql

刚开始在网上搜索了一个测试代码,发现根本就连接不上mysql.

varClient=require('mysql').Client,
client =new Client(),

类似这样的.

查原因:

console.log(require("mysql"));

对象只有5个方法

createConnection

createPool

createQuery

escape

escapeId

没有Client 方法和 属性.

去mysql 模块目录查看了下 Readme.md

#Here is an example on how to use it:

```js
var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'me',
  password : 'secret',
});

connection.connect();

看来网上的代码是有问题.应该是版本更新了不支持了.自己重新写了测试代码运行正常

// mysql.js
//加载mysql Module
var Client = require('mysql');

var db_options = {
    host: "localhost",
    port: 3306,
    user: "root",
    password: "123456",
    database: "drupal"
};
var client = Client.createConnection(db_options);

client.connect();

client.query(
  'SELECT * FROM actions',
  function selectCb(err, results, fields) {
    if (err) {
      throw err;
    }

    console.log(results);
    console.log(fields);
  }
);
client.end();

  

原文地址:https://www.cnblogs.com/shistou/p/3150571.html