- 下载mysql模块
npm install mysql --save
- 创建mysql连接池(connect.js文件)
const mysql = require('mysql');
var mysqlConnect = {};
var pool = mysql.createPool({
connectLimit:10,
host: "localhost",
port: "3306",
user: "root",
password: "root",
database: "2017final"
});
mysqlConnect.sql=function (query,callback) {
if(!query){
callback();
return;
}
pool.query(query,function (err,rows,fields) {
if(err){
callback(err,null);
return;
}
callback(null,rows,fields);
});
};
module.exports = mysqlConnect;
- 测试连接(select.js)
var mysqlConnect = require('./connect');
var selectQuery= "select * from users";
mysqlConnect.sql(selectQuery,function (err,rows,fields) {
if(err){
console.log(err);
return;
}
console.log(JSON.stringify(rows));
});