使用node连接mysql
jopen
9年前
安装依赖库
npm install mysql
创建数据库连接
var mysql = require('mysql'); //定义连接参数 var mysqlConn = { host:'127.0.0.1', user:'user', password:'password', database:'nodejs', port:'3306' }; //创建连接 var conn = mysql.createConnection(mysqlConn); conn.connect(); //执行sql conn.query('select 1+1 as solution ',function(err,rows,fields){ if (err) {throw err;} console.log('select result is '+ rows[0].so); }) //关闭连接? conn.end();
使用数据库连接池
var mysql = require('mysql'); var mysqlConn = { host:'127.0.0.1', user:'root', password:'jt123456', database:'nodejs', port:'3306' }; var pool = mysql.createPool(mysqlConn); // 从连接池获取connection pool.getConnection(function(err,conn){ if (err) { console.log('err when getConnection from pool:'+err); } conn.query('select 1+1 as solution',function(err,rows){ if (err) { consloe.log('err when query sql :'+err); } console.log('solution is '+rows[0].solution); // 释放当前connection conn.release(); }); });
处理连接时的异常
var mysql = require('mysql'); var mysqlConn = { host:'127.0.0.1', user:'root', password:'jt123456', database:'nodejs', port:'3306' }; // 重连 function handleError(){ var conn = mysql.createConnection(mysqlConn); //连接时发生异常就打印错误并在2秒后重连 conn.connect(function(err){ if (err) { console.log('err when connect with mysql server:'+err); }; setTimeout(handleError,2000); }); //监听连接中的异常 conn.on('error',function(err){ console.log('err:'+err); //断开连接时自动重连 if (err.code ==='PROTOCOL_CONNECTION_LOST') { handleError(); }else{ throw err; } }); } handleEror();
参考资料:用Nodejs连接MySQL