Nodejs使用连接池连接数据库

  1. 创建OptPool.js

var mysql = require('mysql');


function OptPool(){

this.flag = true;

this.pool = mysql.createPool({

host:'localhost',

user:'root',

password:'',

database:'mtc',

port:'3306'

});


this.getPool = function(){

if (this.flag) {

this.pool.on('connection',function(connection){

connection.query('SET SESSION auto_increment_increment=1');

this.flag = false;

});

}

return this.pool;

}

}


module.exports = OptPool;

  1. 创建mysqlPool.js

var OptPool = require('./models/OptPool');

var optPool = new OptPool();

var pool = optPool.getPool();


pool.getConnection(function(err,conn){

//删除

var deleteSql = "DELETE FROM mtc_users WHERE user_id = ? ";

var deleteParams = ['3'];

conn.query(deleteSql,deleteParams,function(err,rs){

if (err) {

console.log(err);

return;

}

console.log('delete success');

conn.release();

})


// //修改

// var updateSql = "UPDATE mtc_users SET user_pass = ? WHERE user_id = ? ";

// var updateParams = ['7891012','3'];

// conn.query(updateSql,updateParams,function(err,rs){

//  if (err) {

//  console.log(err);

//  return;

//  }

//  console.log('update success');

//  conn.release();

// })


// //查询

// var selectSql = "SELECT * FROM mtc_users";

// var selectParams = [];

// conn.query(selectSql,selectParams,function(err,rs){

//  if (err) {

//  console.log(err);

//  return;

//  }

//  for(var i = 0;i<rs.length;i++){

//  console.log(rs[i].user_name);

//  }

//  conn.release();

// })

// //插入

// var insertSql = "INSERT INTO mtc_users(user_name,user_pass,create_time) VALUES(?,?,?) ";

// var insertParams = ['zhaoyun','zhao123','123'];

// conn.query(insertSql,insertParams,function(err,rs){

//  if (err) {

//  console.log(err);

//  return;

//  }

//  console.log('insert success');

//  conn.release();

// })

});

本文转自  素颜猪  51CTO博客,原文链接:http://blog.51cto.com/suyanzhu/1891744

上一篇:Nodejs连接数据库


下一篇:Ubuntu18.04下配置深度学习开发环境