nodejs链接mysql
使用mysql连接池:
1.安装mysql支持
npm install mysql
2.安装node.js的mysqlpool模块
npm install -g node-mysql //-g表全局
3.直连mysql
var mysql = require('mysql'); //调用MySQL模块
//创建一个connection
var connection = mysql.createConnection({
host: 'localhost', //主机
user: 'root', //MySQL认证用户名
password: 'root', //MySQL认证用户密码
database: 'mydb',
port: '3306' //端口号
});
//创建一个connection
connection.connect(function(err){
if(err){
console.log('[query] - :'+err);
return;
}
console.log('[connection connect] succeed!');
});
//执行SQL语句
connection.query('SELECT * from users', function(err, rows, fields) {
if (err) {
console.log('[query] - :'+err);
return;
}
console.log('The solution is: ', rows[0].email);
});
//关闭connection
connection.end(function(err){
if(err){
return;
}
console.log('[connection end] succeed!');
});