1、node里面使用mysql
(1)数据库链接
var mysql = require(‘mysql‘); var connection = mysql.createConnection({ host : ‘localhost‘, user : ‘root‘, password : ‘a11111111‘, database : ‘ccl_project_db‘ }); module.exports = connection;
使用:
connection.connect(function(err, conne) { if (err) throw err; const sql = `select * from user`; connection.query(sql, function(err, rows) { if (err) throw err; res.json(rows); }); });
(2)连接池
var mysql = require(‘mysql‘); var pool = mysql.createPool({ host : ‘localhost‘, user : ‘root‘, password : ‘a11111111‘, database : ‘ccl_project_db‘, port: 3306, stringifyObjects: true, //对象类型设置。默认false : RowDataPacket对象 , true : json对象 dateStrings : true, //日期时间类型设置。默认false : 2016-08-31T02:00:32.000Z (UTC通用标准时) , true : 2016-08-31 10:00:32 (常用日期时间格式) }); //数据库连接池 var query=function(sql,options,callback){ pool.getConnection(function(err,conn){ if(err){ callback(err,null,null); }else{ conn.query(sql,options,function(err,results,fields){ //释放连接 conn.release(); //事件驱动回调 callback(err,results,fields); }); } }); }; module.exports = query;
使用:
const sql = `select * from user`; query(sql, ‘‘, function(err,results,fields){ if (err) throw err; res.json(results); });