node.js操作mysql学习笔记

普通连接的增删改查

var mysql  = require('mysql');  //调用MySQL模块

//创建一个connection
var connection = mysql.createConnection({    

    host     : '127.0.0.1',       //主机
    user     : 'root',            //MySQL认证用户名
    password:'12345',
    port:   '3306',
    database: 'node'

});

//创建一个connection,每一次connect只能执行一次query
connection.connect(function(err){
    if(err){       
        console.log('[query] - :'+err);
        return;
    }
    console.log('[connection connect]  succeed!');
}); 

//执行SQL语句,查
connection.query('select * from t_students where name=?',['小明'],function(err,result,fields){
    if(!err){
        console.log(result[0].name);
        fields.forEach(function(v){//fields是一个json数组,每个json包含了字段信息
            console.log(v);
        });
    }
});
//小明
//[connection end] succeed!
//FieldPacket {catalog: "def", db: "node_demo", table: "t_students", orgTable: "t_students", name: //"stu_id", …}
//FieldPacket {catalog: "def", db: "node_demo", table: "t_students", orgTable: "t_students", name: "name", //…}
//FieldPacket {catalog: "def", db: "node_demo", table: "t_students", orgTable: "t_students", name: "age", …}

//关闭connection
connection.end(function(err){
    if(err){       
        return;
    }
    console.log('[connection end] succeed!');
});
改:
var userSql = "update seckill set number = number-1 where seckill_id = ?";
var param = [1000, 2];
connection.query(userSql, param, function (error, result) {
    if(error)
    {
        console.log(error.message);
    }else{
        console.log('affectedRows: '+result.affectedRows);
    }
});
var addVip = 'delete from seckill where seckill_id = 1005';
connection.query(addVip, function(error, result){
    if(error)
    {
        console.log(error.message);
    }else{
        console.log('affectedRows: '+result.affectedRows);
    }
});

连接池

Pool options //mysql的github直接拷贝的,创建pool时的配置
Pools accept all the same options as a connection. When creating a new connection, the options are simply passed to the connection constructor. In addition to those options pools accept a few extras:
acquireTimeout: The milliseconds before a timeout occurs during the connection acquisition. This is slightly different from connectTimeout, because acquiring a pool connection does not always involve making a connection. (Default: 10000)
waitForConnections: Determines the pool's action when no connections are available and the limit has been reached. If true, the pool will queue the connection request and call it when one becomes available. If false, the pool will immediately call back with an error. (Default: true)
connectionLimit: The maximum number of connections to create at once. (Default: 10)
queueLimit: The maximum number of connection requests the pool will queue before returning an error from getConnection. If set to 0, there is no limit to the number of queued connection requests. (Default: 0)

中文释义:
waitForConnections:当连接池没有连接或超出最大限制时,设置为true且会把连接放入队列,设置为false会返回error
connectionLimit:连接数限制,默认:10
queueLimit:最大连接请求队列限制,设置为0表示不限制,默认:0

连接池事件

 acquire
The pool will emit an acquire event when a connection is acquired from the pool. This is called after all acquiring activity has been performed on the connection, right before the connection is handed to the callback of the acquiring code.
pool.on('acquire', function (connection) {
  console.log('Connection %d acquired', connection.threadId);
});
connection
The pool will emit a connection event when a new connection is made within the pool. If you need to set session variables on the connection before it gets used, you can listen to the connection event.
pool.on('connection', function (connection) {
  connection.query('SET SESSION auto_increment_increment=1')
});
enqueue
The pool will emit an enqueue event when a callback has been queued to wait for an available connection.
pool.on('enqueue', function () {
  console.log('Waiting for available connection slot');
});
release
The pool will emit a release event when a connection is released back to the pool. This is called after all release activity has been performed on the connection, so the connection will be listed as free at the time of the event.
pool.on('release', function (connection) {
  console.log('Connection %d released', connection.threadId);
});

连接池示例代码

var mysql = require("mysql");
var pool = mysql.createPool({
    host: '127.0.0.1',    
    user: 'root',
    password:'12345',
    port:'3306',
    database:'node'
});

//监听connection事件
pool.on('connection', function(connection) { 
    connection.query('select * from seckill', function(error, results, fields){
        if (error) {
            throw error;
        }
        if (results) {
            for(var i = 0; i < results.length; i++)
            {
                console.log('%s\t%s',results[i].name,results[i].end_time);
            }
        }
    });

});
//连接池可以直接使用,也可以共享一个连接或管理多个连接(引用官方示例)
//直接使用
pool.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
    if (err) throw err;
    console.log('The solution is: ', rows[0].solution);
});

//共享连接,连接池最常用的方法,可以进一步封装
    pool.getConnection(function(err, connection) {
        connection.query(sql, function(err, result) {   
            console.log(result);
            //释放连接
            connection.release();
        });

        //Error: Connection already released,应该每次到连接池中再次获取
        // connection.query( 'SELECT * FROM seckill;', function(err, result) {
        //  console.log(result);
        //  connection.release();
        // });
    });
myQuery('SELECT * FROM seckill;');
myQuery('SELECT * FROM seckill;');

//连接池的关闭,一般用不到。除非项目停止运行
pool.end(function (err) {
  // all connections in the pool have ended
});

以下为封装后的js,单独列为一个js文件然后导出

var db    = {};  
var mysql = require('mysql');  
var pool  = mysql.createPool({  
  connectionLimit : 10,  
  host  : 'localhost',  
  user  : 'root',  
  password  : '123456',  
  database : 'nodejs'  
});  
  
//获取连接  
db.getConnection = function(callback){  
   pool.getConnection(function(err, connection) {  
      if (err) {  
            callback(null);  
           return;  
       }  
       callback(connection);  
   });  
}   
module.exports = db;  

连接池集群

//创建连接池集群
var poolCluster = mysql.createPoolCluster();
//添加配置 config是一个连接池配置
poolCluster.add(config);//使用自动名称添加配置
poolCluster.add('MASTER',masterConfig);//添加命名配置
poolCluster.add('SLAVE1',slave1config);
poolCluster.add('SLAVE2',slave2config);

//删除配置
poolCluster.remove('SLAVE1');//根据配置名字
poolCluster.remove('SLAVE*')//根据匹配到的

//获取连接 从所有的连接池里获得 默认选择器 
poolCluster.getConnectiuon(function(err,connection){});

//从 一个连接池里面获取连接
poolCluster.getConnectiuon('MASTER',function(err,connection){});
//从匹配到的连接池组里面获取连接 按照顺序
//如果SLAVE1出错 就从SLAVE2获得连接
poolCluster.getConnectiuon('SLAVE*','ORDER',function(err,connection){} );

//触发事件 当删除连接池时触发
poolCluster.on('remove',function(nodeId){
    console.log(nodeId);//被删除的连接池名字
});
//配置 选择器 从SLAVE1 SLAVE2 里面随机获得连接
var pool = poolCluster.of('SLAVE*','RANDOM');
pool.getConnectiuon(function(err,connection){});

//关闭连接池集群
poolCluster.end();

简单事务

Transactions事务
Simple transaction support is available at the connection level:
connection.beginTransaction(function(err) {
  if (err) { throw err; }
  connection.query('INSERT INTO posts SET title=?', title, function (error, results, fields) {
    if (error) {
      return connection.rollback(function() {
        throw error;
      });
    }

    var log = 'Post ' + results.insertId + ' added';

    connection.query('INSERT INTO log SET data=?', log, function (error, results, fields) {
      if (error) {
        return connection.rollback(function() {
          throw error;
        });
      }
      connection.commit(function(err) {
        if (err) {
          return connection.rollback(function() {
            throw err;
          });
        }
        console.log('success!');
      });
    });
  });
});

mysql官方文档https://www.npmjs.com/package/node-mysql

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,558评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,002评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,036评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,024评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,144评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,255评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,295评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,068评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,478评论 1 305
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,789评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,965评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,649评论 4 336
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,267评论 3 318
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,982评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,223评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,800评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,847评论 2 351

推荐阅读更多精彩内容