时间:2021-07-01 10:21:17 帮助过:3人阅读
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编码避免乱码。
标签: