标签:
步骤如下:
1.设置连接属性,允许多重sql语句:
multipleStatements: true
const pool = mysql.createPool({ connectionLimit: 50, host: ‘localhost‘, user: ‘root‘, password: ‘******‘, database: "databasename",
// databasename不要用大写,否则找不到数据库.(windows下支持大写自动转小写,linux下仅支持小写) multipleStatements: true });
2.在sql语句前添加“SET NAMES ‘utf8‘; ”来设置链接,平台,结果编码形式
3.在回调函数调用时,不用apply(null,arguments)而是apply(null,[err,results[1],fields])
// 以插入数据为例 function insertSql(table, obj, callback) { let sqlstr = ""; let names = []; let values = []; if (_.isEmpty(obj)) { sqlstr = `INSERT INTO ${table} VALUES()`; } else { for (let data in obj) { names.push(data.toString()); values.push(obj[data].toString()); } sqlstr = `INSERT INTO ${table} (${names.join(‘,‘)}) VALUES(${‘"‘ + values.join(‘","‘) + ‘"‘})`; } console.log(sqlstr); pool.getConnection(function (err, connection) { // Use the connection connection.query("SET NAMES ‘utf8‘; " + sqlstr, function (err, results, fields) { // And done with the connection. connection.release(); // Don‘t use the connection here, it has been returned to the pool. callback.apply(null, [err,results[1],fields]); }); }); }
nodejs+mysql,链接mysql处理数据强制使用UTF-8编码避免乱码。
标签:
原文地址:http://www.cnblogs.com/Totooria-Hyperion/p/5639322.html