Node.mysql

mysql为常用数据库,下面简单记录在nodejs中操作mysql数据库的简单实现。

环境:

nodejs4.2.2

mysql5.7.12

win7

参考资料:

npm mysql

代码


var mysql=require("mysql");
var conn = require('../../config/conn.json');
var mysqlHander = module.exports;


/*
** * 数据库连接配置信息 */ var pool = mysql.createPool({ host: conn.mysql.houstName, user: conn.mysql.userName, password: conn.mysql.userPassword, database: conn.mysql.dbName, port: conn.mysql.hostPort }); /** * mysql数据连接池 * @param sql * @param callback */ var query = function(sql,param,callback){ if(param === undefined){ pool.getConnection(function(err,conn){ if(err){ callback(err,null,null); }else{ conn.query(sql,function(qerr,vals,fields){ //释放连接 conn.release(); //事件驱动回调 callback(qerr,vals,fields); }); } }); }else { pool.getConnection(function(err,conn){ if(err){ callback(err,null,null); }else{ conn.query(sql,param,function(qerr,vals,fields){ //释放连接 conn.release(); //事件驱动回调 callback(qerr,vals,fields); }); } }); } pool.on('error',handleError); }; /** * 连接异常退出 打开新的连接 * @param err */ function handleError (err) { console.log('数据访问异常退出...正在尝试重新建立连接'); if (err) { // 如果是连接断开,自动重新连接 if (err.code === 'PROTOCOL_CONNECTION_LOST') { connect(); console.log('尝试重新打开连接...'); } else { console.error(err.stack || err); console.log('尝试重新建立连接失败!请检查数据访问,文件位置:'+ __dirname); console.log(err); } } } /** * 数据操作 * @param callBack */ mysqlHander.query = function (callBack) { query(mysqlHander.sql,mysqlHander.param, function (err,rows,filed) { if(err) console.log(err); callBack(err,rows,filed); }); }
原文地址:https://www.cnblogs.com/z-yue/p/5717087.html