nodejs中mysql用法

来源:互联网 发布:unity3d文件如何打开 编辑:程序博客网 时间:2024/06/07 13:10

1、建立数据库连接:createConnection(Object)方法
      该方法接受一个对象作为参数,该对象有四个常用的属性host,user,password,database。与php中链接数据库的参数相同。属性列表如下:
view plaincopy to clipboardprint?
  1.         host: 连接数据库所在的主机名. (默认: localhost)  
  2.   port: 连接端口. (默认: 3306)  
  3.   localAddress: 用于TCP连接的IP地址. (可选)  
  4.   socketPath: 链接到unix域的路径。在使用host和port时该参数会被忽略.  
  5.   user: MySQL用户的用户名.  
  6.   password: MySQL用户的密码.  
  7.   database: 链接到的数据库名称 (可选).  
  8.   charset: 连接的字符集. (默认: 'UTF8_GENERAL_CI'.设置该值要使用大写!)  
  9.   timezone: 储存本地时间的时区. (默认: 'local')  
  10.   stringifyObjects: 是否序列化对象. See issue #501. (默认: 'false')  
  11.   insecureAuth: 是否允许旧的身份验证方法连接到数据库实例. (默认: false)  
  12.   typeCast: 确定是否讲column值转换为本地JavaScript类型列值. (默认: true)  
  13.   queryFormat: 自定义的查询语句格式化函数.  
  14.   supportBigNumbers: 数据库处理大数字(长整型和含小数),时应该启用 (默认: false).  
  15.   bigNumberStrings: 启用 supportBigNumbers和bigNumberStrings 并强制这些数字以字符串的方式返回(默认: false).   
  16.   dateStrings: 强制日期类型(TIMESTAMP, DATETIME, DATE)以字符串返回,而不是一javascript Date对象返回. (默认: false)  
  17.   debug: 是否开启调试. (默认: false)  
  18.   multipleStatements: 是否允许在一个query中传递多个查询语句. (Default: false)  
  19.   flags: 链接标志.  

还可以使用字符串连接数据库例如:
view plaincopy to clipboardprint?
  1. var connection = mysql.createConnection('mysql://user:pass@host/db?debug=true&charset=BIG5_CHINESE_CI&timezone=-0700');  


view plaincopy to clipboardprint?
  1. /** 
  2.  * Created by Pad on 14-4-14. 
  3.  */  
  4. //连接数据库  
  5. var mysql      = require('mysql');  
  6. var connection = mysql.createConnection({  
  7.     host     : '数据库地址',  
  8.     user     : '数据库用户',  
  9.     password : '密码',  
  10.     multipleStatements: true //开启多条语句同时执行  
  11. });  
  12. connection.connect();  
  13.   
  14. //查询1  
  15. connection.query("SELECT 1 as `from`,2 as `to`,3 as `type`;SELECT id,name from test.`user`", function(err, rows1, fields) {  
  16.     if (err) throw err;  
  17.     console.log('The 1 is:\n ', rows1);  
  18. });  
  19.   
  20. //关闭连接  
  21. connection.end();  


输出
view plaincopy to clipboardprint?
  1.   [ [ { from: 1, to: 2, type: 3 } ],  
  2.   [ { id: 1, name: 'tommy.hu' },  
  3.     { id: 3, name: 'jack.chen' },  
  4.     { id: 2, name: 'naci.liu' },  
  5.     { id: 4, name: 'sophia.li' },  
  6.     { id: 5, name: 'tony.hu' } ] ]  



2、结束数据库连接end()和destroy()
end()接受一个回调函数,并且会在query结束之后才触发,如果query出错,仍然会终止链接,错误会传递到回调函数中处理。
destroy()立即终止数据库连接,即使还有query没有完成,之后的回调函数也不会在触发。

3、创建连接池 createPool(Object)  Object和createConnection参数相同。
可以监听connection事件,并设置session值
view plaincopy to clipboardprint?
  1. pool.on('connection', function(connection) {    
  2.         connection.query('SET SESSION auto_increment_increment=1')    
  3.     });    

connection.release()释放链接到连接池。如果需要关闭连接并且删除,需要使用connection.destroy()
pool除了接受和connection相同的参数外,还接受几个扩展的参数
view plaincopy to clipboardprint?
  1. createConnection: 用于创建链接的函数. (Default: mysql.createConnection)    
  2.     waitForConnections: 决定当没有连接池或者链接数打到最大值时pool的行为. 为true时链接会被放入队列中在可用是调用,为false时会立即返回error. (Default: true)    
  3.     connectionLimit: 最大连接数. (Default: 10)    



4、连接池集群
允许不同的host链接
view plaincopy to clipboardprint?
  1. // create    
  2.     var poolCluster = mysql.createPoolCluster();    
  3.     
  4.     poolCluster.add(config); // anonymous group    
  5.     poolCluster.add('MASTER', masterConfig);    
  6.     poolCluster.add('SLAVE1', slave1Config);    
  7.     poolCluster.add('SLAVE2', slave2Config);    
  8.     
  9.     // Target Group : ALL(anonymous, MASTER, SLAVE1-2), Selector : round-robin(default)    
  10.     poolCluster.getConnection(function (err, connection) {});    
  11.     
  12.     // Target Group : MASTER, Selector : round-robin    
  13.     poolCluster.getConnection('MASTER', function (err, connection) {});    
  14.     
  15.     // Target Group : SLAVE1-2, Selector : order    
  16.     // If can't connect to SLAVE1, return SLAVE2. (remove SLAVE1 in the cluster)    
  17.     poolCluster.on('remove', function (nodeId) {    
  18.       console.log('REMOVED NODE : ' + nodeId); // nodeId = SLAVE1     
  19.     });    
  20.     
  21.     poolCluster.getConnection('SLAVE*''ORDER', function (err, connection) {});    
  22.     
  23.     // of namespace : of(pattern, selector)    
  24.     poolCluster.of('*').getConnection(function (err, connection) {});    
  25.     
  26.     var pool = poolCluster.of('SLAVE*''RANDOM');    
  27.     pool.getConnection(function (err, connection) {});    
  28.     pool.getConnection(function (err, connection) {});    
  29.     
  30.     // destroy    
  31.     poolCluster.end();    


链接集群的可选参数
view plaincopy to clipboardprint?
  1. canRetry: 值为true时,允许连接失败时重试(Default: true)    
  2.     removeNodeErrorCount: 当连接失败时 errorCount 值会增加. 当errorCount 值大于 removeNodeErrorCount 将会从PoolCluster中删除一个节点. (Default: 5)    
  3.     defaultSelector: 默认选择器. (Default: RR)    
  4.         RR: 循环. (Round-Robin)    
  5.         RANDOM: 通过随机函数选择节点.    
  6.         ORDER: 无条件地选择第一个可用节点.    



5、切换用户/改变连接状态
view plaincopy to clipboardprint?
  1. Mysql允许在比断开连接的的情况下切换用户    
  2.     connection.changeUser({user : 'john'}, function(err) {    
  3.         if (err) throw err;    
  4.     });    


view plaincopy to clipboardprint?
  1. 参数    
  2.     user: 新的用户 (默认为早前的一个).    
  3.     password: 新用户的新密码 (默认为早前的一个).    
  4.     charset: 新字符集 (默认为早前的一个).    
  5.     database: 新数据库名称 (默认为早前的一个).    



6、处理服务器连接断开
view plaincopy to clipboardprint?
  1. var db_config = {  
  2.       host: 'localhost',  
  3.       user: 'root',  
  4.       password: '',  
  5.       database: 'example'  
  6.   };  
  7.   
  8.   var connection;  
  9.   
  10.   function handleDisconnect() {  
  11.     connection = mysql.createConnection(db_config); // Recreate the connection, since  
  12.                                                     // the old one cannot be reused.  
  13.   
  14.     connection.connect(function(err) {              // The server is either down  
  15.       if(err) {                                     // or restarting (takes a while sometimes).  
  16.         console.log('error when connecting to db:', err);  
  17.         setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,  
  18.       }                                     // to avoid a hot loop, and to allow our node script to  
  19.     });                                     // process asynchronous requests in the meantime.  
  20.                                             // If you're also serving http, display a 503 error.  
  21.     connection.on('error', function(err) {  
  22.       console.log('db error', err);  
  23.       if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually  
  24.         handleDisconnect();                         // lost due to either server restart, or a  
  25.       } else {                                      // connnection idle timeout (the wait_timeout  
  26.         throw err;                                  // server variable configures this)  
  27.       }  
  28.     });  
  29.   }  
  30.   
  31.   handleDisconnect();  



7、转义查询值
为了避免SQL注入攻击,需要转义用户提交的数据。可以使用connection.escape() 或者 pool.escape()
例如:
view plaincopy to clipboardprint?
  1. var userId = 'some user provided value';  
  2.   var sql    = 'SELECT * FROM users WHERE id = ' + connection.escape(userId);  
  3.   connection.query(sql, function(err, results) {  
  4.     // ...  
  5.   });  
  6.   或者使用?作为占位符  
  7.   connection.query('SELECT * FROM users WHERE id = ?', [userId], function(err, results) {  
  8.     // ...  
  9.   });  
  10.   不同类型值的转换结果  
  11.   Numbers 不变  
  12.   Booleans 转换为字符串 'true' / 'false'   
  13.   Date 对象转换为字符串 'YYYY-mm-dd HH:ii:ss'  
  14.   Buffers 转换为是6进制字符串  
  15.   Strings 不变  
  16.   Arrays => ['a''b'] 转换为 'a''b'  
  17.   嵌套数组 [['a''b'], ['c''d']] 转换为 ('a''b'), ('c''d')  
  18.   Objects 转换为 key = 'val' pairs. 嵌套对象转换为字符串.  
  19.   undefined / null ===> NULL  
  20.   NaN / Infinity 不变. MySQL 不支持这些值,  除非有工具支持,否则插入这些值会引起错误.  
  21.   转换实例:  
  22.   var post  = {id: 1, title: 'Hello MySQL'};  
  23.   var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {  
  24.     // Neat!  
  25.   });  
  26.   console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'  
  27.   或者手动转换  
  28.   var query = "SELECT * FROM posts WHERE title=" + mysql.escape("Hello MySQL");  
  29.   
  30.   console.log(query); // SELECT * FROM posts WHERE title='Hello MySQL'  




8、转换查询标识符
如果不能信任SQL标识符(数据库名、表名、列名),可以使用转换方法mysql.escapeId(identifier);
view plaincopy to clipboardprint?
  1. var sorter = 'date';  
  2.   var query = 'SELECT * FROM posts ORDER BY ' + mysql.escapeId(sorter);  
  3.   
  4.   console.log(query); // SELECT * FROM posts ORDER BY `date`  
  5.   支持转义多个  
  6.   var sorter = 'date';  
  7.   var query = 'SELECT * FROM posts ORDER BY ' + mysql.escapeId('posts.' + sorter);  
  8.   
  9.   console.log(query); // SELECT * FROM posts ORDER BY `posts`.`date`  
  10.   可以使用??作为标识符的占位符  
  11.   var userId = 1;  
  12.   var columns = ['username''email'];  
  13.   var query = connection.query('SELECT ?? FROM ?? WHERE id = ?', [columns, 'users', userId], function(err, results) {  
  14.     // ...  
  15.   });  
  16.   
  17.   console.log(query.sql); // SELECT `username`, `email` FROM `users` WHERE id = 1  


9、准备查询
可以使用mysql.format来准备查询语句,该函数会自动的选择合适的方法转义参数。
view plaincopy to clipboardprint?
  1. var sql = "SELECT * FROM ?? WHERE ?? = ?";  
  2.   var inserts = ['users''id', userId];  
  3.   sql = mysql.format(sql, inserts);  
  4.   10、自定义格式化函数  
  5.   connection.config.queryFormat = function (query, values) {  
  6.     if (!values) return query;  
  7.     return query.replace(/\:(\w+)/g, function (txt, key) {  
  8.       if (values.hasOwnProperty(key)) {  
  9.         return this.escape(values[key]);  
  10.       }  
  11.       return txt;  
  12.     }.bind(this));  
  13.   };  
  14.   
  15.   connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" });  



11、获取插入行的id
当使用自增主键时获取插入行id,如:
view plaincopy to clipboardprint?
  1. connection.query('INSERT INTO posts SET ?', {title: 'test'}, function(err, result) {  
  2.     if (err) throw err;  
  3.   
  4.     console.log(result.insertId);  
  5.   });  


12、流处理
有时你希望选择大量的行并且希望在数据到达时就处理他们,你就可以使用这个方法
view plaincopy to clipboardprint?
  1. var query = connection.query('SELECT * FROM posts');  
  2.   query  
  3.     .on('error', function(err) {  
  4.       // Handle error, an 'end' event will be emitted after this as well  
  5.     })  
  6.     .on('fields', function(fields) {  
  7.       // the field packets for the rows to follow  
  8.     })  
  9.     .on('result', function(row) {  
  10.       // Pausing the connnection is useful if your processing involves I/O  
  11.       connection.pause();  
  12.   
  13.       processRow(row, function() {  
  14.         connection.resume();  
  15.       });  
  16.     })  
  17.     .on('end', function() {  
  18.       // all rows have been received  
  19.     });  


13、混合查询语句(多语句查询)
因为混合查询容易被SQL注入攻击,默认是不允许的,可以使用var connection = mysql.createConnection({multipleStatements: true});开启该功能。
混合查询实例:
view plaincopy to clipboardprint?
  1. connection.query('SELECT 1; SELECT 2', function(err, results) {  
  2.     if (err) throw err;  
  3.   
  4.     // `results` is an array with one element for every statement in the query:  
  5.     console.log(results[0]); // [{1: 1}]  
  6.     console.log(results[1]); // [{2: 2}]  
  7.   });  

同样可以使用流处理混合查询结果:
view plaincopy to clipboardprint?
  1. var query = connection.query('SELECT 1; SELECT 2');  
  2.   
  3.   query  
  4.     .on('fields', function(fields, index) {  
  5.       // the fields for the result rows that follow  
  6.     })  
  7.     .on('result', function(row, index) {  
  8.       // index refers to the statement this result belongs to (starts at 0)  
  9.     });  

如果其中一个查询语句出错,Error对象会包含err.index指示错误语句的id,整个查询也会终止。
混合查询结果的流处理方式是做实验性的,不稳定。

14、事务处理
connection级别的简单事务处理
view plaincopy to clipboardprint?
  1. connection.beginTransaction(function(err) {  
  2.     if (err) { throw err; }  
  3.     connection.query('INSERT INTO posts SET title=?', title, function(err, result) {  
  4.       if (err) {   
  5.         connection.rollback(function() {  
  6.           throw err;  
  7.         });  
  8.       }  
  9.   
  10.       var log = 'Post ' + result.insertId + ' added';  
  11.   
  12.       connection.query('INSERT INTO log SET data=?', log, function(err, result) {  
  13.         if (err) {   
  14.           connection.rollback(function() {  
  15.             throw err;  
  16.           });  
  17.         }    
  18.         connection.commit(function(err) {  
  19.           if (err) {   
  20.             connection.rollback(function() {  
  21.               throw err;  
  22.             });  
  23.           }  
  24.           console.log('success!');  
  25.         });  
  26.       });  
  27.     });  
  28.   });  
0 0
原创粉丝点击