微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

node操作mysql数据库实例详解

本文实例讲述了node操作MysqL数据库方法分享给大家供大家参考,具体如下:

1、建立数据库连接

createConnection(Object)方法

方法接受一个对象作为参数,该对象有四个常用的属性host,user,password,database。与PHP链接数据库的参数相同。属性列表如下:

数据库所在的主机名. (认: localhost)默认: 3306)链接到unix域的路径。在使用host和port时该参数会被忽略.MysqL用户用户名.MysqL用户的密码.链接到的数据库名称 (可选).默认: 'UTF8_GENERAL_CI'.设置该值要使用大写!)间的时区. (认: 'local')默认: 'false')方法连接到数据库实例. (认: false)默认: true)自定义的查询语句格式化函数.数据库处理大数字(长整型和含小数),时应该启用 (认: false).默认: false).默认: false)默认: false)一个query中传递多个查询语句. (Default: false)链接标志.

还可以使用字符串连接数据库例如:

rush:js;"> var connection = MysqL.createConnection('MysqL://user:pass@host/db?debug=true&charset=BIG5_CHInesE_CI&timezone=-0700');

2、结束数据库连接

end()destroy()

end()接受一个回调函数,并且会在query结束之后才触发,如果query出错,仍然会终止链接错误会传递到回调函数中处理。

destroy()立即终止数据库连接,即使还有query没有完成,之后的回调函数也不会在触发。

3、创建连接池

createPool(Object) Object和createConnection参数相同。

可以监听connection事件,并设置session值

rush:js;"> pool.on('connection',function(connection) { connection.query('SET SESSION auto_increment_increment=1') });

connection.release()释放链接到连接池。如果需要关闭连接并且删除,需要使用connection.destroy()

pool除了接受和connection相同的参数外,还接受几个扩展的参数

链接的函数. (Default: MysqL.createConnection)链接数打到最大值时pool的行为. 为true时链接会被放入队列中在可用是调用,为false时会立即返回error. (Default: true)

4、连接池集群

允许不同的host链接

rush:js;"> // create var poolCluster = MysqL.createPoolCluster(); poolCluster.add(config); // anonymous group poolCluster.add('MASTER',masterConfig); poolCluster.add('SLAVE1',slave1Config); poolCluster.add('SLAVE2',slave2Config); // Target Group : ALL(anonymous,MASTER,SLAVE1-2),Selector : round-robin(default) poolCluster.getConnection(function (err,connection) {}); // Target Group : MASTER,Selector : round-robin poolCluster.getConnection('MASTER',function (err,connection) {}); // Target Group : SLAVE1-2,Selector : order // If can't connect to SLAVE1,return SLAVE2. (remove SLAVE1 in the cluster) poolCluster.on('remove',function (nodeId) { console.log('REMOVED NODE : ' + nodeId); // nodeId = SLAVE1 }); poolCluster.getConnection('SLAVE*','ORDER',connection) {}); // of namespace : of(pattern,selector) poolCluster.of('*').getConnection(function (err,connection) {}); var pool = poolCluster.of('SLAVE*','RANDOM'); pool.getConnection(function (err,connection) {}); pool.getConnection(function (err,connection) {}); // destroy poolCluster.end();

链接集群的可选参数

增加. 当errorCount 值大于 removeNodeErrorCount 将会从PoolCluster中删除一个节点. (Default: 5)默认选择器. (Default: RR)随机函数选择节点.一个可用节点.

5、切换用户/改变连接状态

MysqL允许在比断开连接的的情况下切换用户

rush:js;"> connection.changeUser({user : 'john'},function(err) { if (err) throw err; });

参数

用户 (认为早前的一个).新用户的新密码 (认为早前的一个).默认为早前的一个).数据库名称 (认为早前的一个).

6、处理服务器连接断开

rush:js;"> var db_config = { host: 'localhost',user: 'root',password: '',database: 'example' }; var connection; function handledisconnect() { connection = MysqL.createConnection(db_config); // Recreate the connection,since // the old one cannot be reused. connection.connect(function(err) { // The server is either down if(err) { // or restarting (takes a while sometimes). console.log('error when connecting to db:',err); setTimeout(handledisconnect,2000); // We introduce a delay before attempting to reconnect,} // to avoid a hot loop,and to allow our node script to }); // process asynchronous requests in the meantime. // If you're also serving http,display a 503 error. connection.on('error',function(err) { console.log('db error',err); if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MysqL server is usually handledisconnect(); // lost due to either server restart,or a } else { // connnection idle timeout (the wait_timeout throw err; // server variable configures this) } }); } handledisconnect();

7、转义查询

为了避免sql注入攻击,需要转义用户提交的数据。可以使用connection.escape() 或者 pool.escape()

例如:

rush:js;"> var userId = 'some user provided value'; var sql = 'SELECT * FROM users WHERE id = ' + connection.escape(userId); connection.query(sql,function(err,results) { // ... });

或者使用?作为占位符

rush:js;"> connection.query('SELECT * FROM users WHERE id = ?',[userId],results) { // ... });

不同类型值的转换结果

['a','b'] 转换为 'a','b' 嵌套数组 [['a','b'],['c','d']] 转换为 ('a','b'),('c','d') Objects 转换为 key = 'val' pairs. 嵌套对象转换为字符串. undefined / null ===> NULL NaN / Infinity 不变. MysqL 不支持这些值,除非有工具支持,否则插入这些值会引起错误.

转换实例:

rush:js;"> var post = {id: 1,title: 'Hello MysqL'}; var query = connection.query('INSERT INTO posts SET ?',post,result) { // Neat! }); console.log(query.sql); // INSERT INTO posts SET `id` = 1,`title` = 'Hello MysqL'

或者手动转换

rush:js;"> var query = "SELECT * FROM posts WHERE title=" + MysqL.escape("Hello MysqL"); console.log(query); // SELECT * FROM posts WHERE title='Hello MysqL'

8、转换查询标识符

如果不能信任sql标识符(数据库名、表名、列名),可以使用转换方法MysqL.escapeId(identifier);

rush:js;"> var sorter = 'date'; var query = 'SELECT * FROM posts ORDER BY ' + MysqL.escapeId(sorter); console.log(query); // SELECT * FROM posts ORDER BY `date`

支持转义多个

rush:js;"> var sorter = 'date'; var query = 'SELECT * FROM posts ORDER BY ' + MysqL.escapeId('posts.' + sorter); console.log(query); // SELECT * FROM posts ORDER BY `posts`.`date`

可以使用??作为标识符的占位符

rush:js;"> var userId = 1; var columns = ['username','email']; var query = connection.query('SELECT ?? FROM ?? WHERE id = ?',[columns,'users',userId],results) { // ... }); console.log(query.sql); // SELECT `username`,`email` FROM `users` WHERE id = 1

9、准备查询

可以使用MysqL.format来准备查询语句,该函数自动的选择合适的方法转义参数。

rush:js;"> var sql = "SELECT * FROM ?? WHERE ?? = ?"; var inserts = ['users','id',userId]; sql = MysqL.format(sql,inserts);

10、自定义格式化函数

rush:js;"> connection.config.queryFormat = function (query,values) { if (!values) return query; return query.replace(/\:(\w+)/g,function (txt,key) { if (values.hasOwnProperty(key)) { return this.escape(values[key]); } return txt; }.bind(this)); }; connection.query("UPDATE posts SET title = :title",{ title: "Hello MysqL" });

11、获取插入行的id

当使用自增主键时获取插入行id,如:

rush:js;"> connection.query('INSERT INTO posts SET ?',{title: 'test'},result) { if (err) throw err; console.log(result.insertId); });

12、流处理

有时你希望选择大量的行并且希望在数据到达时就处理他们,你就可以使用这个方法

rush:js;"> var query = connection.query('SELECT * FROM posts'); query .on('error',function(err) { // Handle error,an 'end' event will be emitted after this as well }) .on('fields',function(fields) { // the field packets for the rows to follow }) .on('result',function(row) { // Pausing the connnection is useful if your processing involves I/O connection.pause(); processRow(row,function() { connection.resume(); }); }) .on('end',function() { // all rows have been received });

13、混合查询语句(多语句查询

因为混合查询容易被sql注入攻击,认是不允许的,可以使用:

rush:js;"> var connection = MysqL.createConnection({multipleStatements: true});

开启该功能

混合查询实例:

rush:js;"> connection.query('SELECT 1; SELECT 2',results) { if (err) throw err; // `results` is an array with one element for every statement in the query: console.log(results[0]); // [{1: 1}] console.log(results[1]); // [{2: 2}] });

同样可以使用流处理混合查询结果:

rush:js;"> var query = connection.query('SELECT 1; SELECT 2'); query .on('fields',function(fields,index) { // the fields for the result rows that follow }) .on('result',function(row,index) { // index refers to the statement this result belongs to (starts at 0) });

如果其中一个查询语句出错,Error对象会包含err.index指示错误语句的id,整个查询也会终止。

混合查询结果的流处理方式是做实验性的,不稳定。

14、事务处理

connection级别的简单事务处理

rush:js;"> connection.beginTransaction(function(err) { if (err) { throw err; } connection.query('INSERT INTO posts SET title=?',title,result) { if (err) { connection.rollback(function() { throw err; }); } var log = 'Post ' + result.insertId + ' added'; connection.query('INSERT INTO log SET data=?',log,result) { if (err) { connection.rollback(function() { throw err; }); } connection.commit(function(err) { if (err) { connection.rollback(function() { throw err; }); } console.log('success!'); }); }); }); });

15、错误处理

boolean

更详细的说明请查看:https://github.com/Felixge/node-MysqL

希望本文所述对大家nodejs程序设计有所帮助。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐