安装mysql模块
npm install mysql
测试是否连接成功
mysql.js代码:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123456',
database : 'nodejs'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) {
console.log(err);
return;
};
console.log('The solution is: ', rows[0].solution);
});
connection.end();
结果 : 连接成功
image封装连接数据库代码
支持连接池,mysql.js:
var db = {};
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host : 'localhost',
user : 'root',
password : '123456',
database : 'nodejs'
});
db.query = function(sql, callback){
if (!sql) {
callback();
return;
}
pool.query(sql, function(err, rows, fields) {
if (err) {
console.log(err);
callback(err, null);
return;
};
callback(null, rows, fields);
});
}
module.exports = db;
测试封装
dbtest.js:
var db = require('./mysql.js');
var sql = 'SELECT count(*) as count from user';
db.query(sql, function(err, rows, fields){
if (err) {
console.log(err);
return;
}
console.log('用户数量 : ', rows[0].count);
});
运行结果
image数据库截图:
image
网友评论