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();
七、转义查询值
为了避免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'
八、转换查询标识符
如果不能信任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` 可以使用??作为标识符的占位符 var userId = 1; var columns = ['username', 'email']; var query = connection.query('SELECT ?? FROM ?? WHERE id = ?', [columns, 'users', userId], function(err, results) { // ... }); console.log(query.sql); // SELECT `username`, `email` FROM `users` WHERE id = 1
九、准备查询
可以使用mysql.format来准备查询语句,该函数会自动的选择合适的方法转义参数。
var sql = "SELECT * FROM ?? WHERE ?? = ?"; var inserts = ['users', 'id', userId]; sql = mysql.format(sql, inserts); 10、自定义格式化函数 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" });
十、获取插入行的id
当使用自增主键时获取插入行id,如:
connection.query('INSERT INTO posts SET ?', {title: 'test'}, function(err, result) { if (err) throw err; console.log(result.insertId); });
十一、流处理
有时你希望选择大量的行并且希望在数据到达时就处理他们,你就可以使用这个方法