本篇教程介绍了Node.js链接mysql处理数据强制使用UTF-8编码避免乱码详解,希望阅读本篇文章以后大家有所收获,帮助大家对Node.js的理解更加深入。
<
步骤如下:
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]);
});
});
}
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注WEB前端Node.js频道!