canRetry
值为true时,允许连接失败时重试(Default: true)
removeNodeErrorCount
当连接失败时 errorCount 值会增加. 当errorCount 值大于 removeNodeErrorCount 将会从PoolCluster中删除一个节点. (Default: 5)
defaultSelector
默认选择器. (Default: RR)
RR
循环. (Round-Robin)
RANDOM
通过随机函数选择节点.
ORDER
无条件地选择第一个可用节点.
5、切换用户/改变连接状态
Mysql允许在比断开连接的的情况下切换用户
connection.changeUser({user : 'john'}, function(err) { if (err) throw err; });
参数
user
新的用户 (默认为早前的一个).
password
新用户的新密码 (默认为早前的一个).
charset
新字符集 (默认为早前的一个).
database
新数据库名称 (默认为早前的一个).
6、处理服务器连接断开
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()
例如:
var userId = 'some user provided value'; var sql = 'SELECT * FROM users WHERE id = ' + connection.escape(userId); connection.query(sql, function(err, results) { // ... });
或者使用?作为占位符
connection.query('SELECT * FROM users WHERE id = ?', [userId], function(err, results) { // ... });
不同类型值的转换结果
Numbers 不变
Booleans 转换为字符串 'true' / 'false'
Date 对象转换为字符串 'YYYY-mm-dd HH:ii:ss'
Buffers 转换为是6进制字符串
Strings 不变
Arrays => ['a', 'b'] 转换为 'a', 'b'
嵌套数组 [['a', 'b'], ['c', 'd']] 转换为 ('a', 'b'), ('c', 'd')
Objects 转换为 key = 'val' pairs. 嵌套对象转换为字符串.
undefined / null ===> NULL
NaN / Infinity 不变. MySQL 不支持这些值, 除非有工具支持,否则插入这些值会引起错误.
转换实例:
var post = {id: 1, title: 'Hello MySQL'}; var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) { // Neat! }); console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
或者手动转换
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);
var sorter = 'date'; var query = 'SELECT * FROM posts ORDER BY ' + mysql.escapeId(sorter); console.log(query); // SELECT * FROM posts ORDER BY `date`
支持转义多个
var sorter = 'date'; var query = 'SELECT * FROM posts ORDER BY ' + mysql.escapeId('posts.' + sorter); console.log(query); // SELECT * FROM posts ORDER BY `posts`.`date`
可以使用??作为标识符的占位符