首页 > 代码库 > NodeJS使用mysql

NodeJS使用mysql

1.环境准备

手动添加数据库依赖:

在package.json的dependencies中新增, “mysql” : “latest”,

{
  "name": "news",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.13.2",
    "cookie-parser": "~1.3.5",
    "debug": "~2.2.0",
    "express": "~4.13.1",
    "jade": "~1.11.0",
    "morgan": "~1.6.1",
    "serve-favicon": "~2.3.0",
    "mysql":"latest"
  }
}

使用命令安装mysql并添加依赖:

npm install mysql -save

  

2.官方例子:

复制代码
//连接数据库
var mysql = require(‘mysql‘);
var connection = mysql.createConnection({
    host: ‘localhost‘,
    user: ‘root‘,
    password: ‘open00‘,
    database:‘test‘
});

connection.connect();
//查询
connection.query(‘select * from `mytable`‘, function(err, rows, fields) {
    if (err) throw err;
    console.log(‘查询结果为: ‘, rows);
});
//关闭连接
connection.end();

运行node

技术分享

  

NodeJS使用mysql