javascript – 使用node-mysql时的SQL Parse错误
作者:互联网
当我尝试使用node-mysql在MYSQL数据库上调用查询时,我遇到了解析错误.我很确定查询有效.毫无疑问,它通过phpmyadmin运行.
Message.save = function(message, callback){
db.query("INSERT INTO e_message (chatid, message, userid) VALUES(" + message.chatid + ", '" + message.message +"', " + message.userid + "); SELECT * FROM e_message WHERE chatid = " + message.chatid + " ORDER BY timestamp DESC LIMIT 0, 1;",
function(err, rows, fields){
console.log(err);
callback(err, new Message(rows[0]));
});
}
我收到了以下错误:
{ [Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT * FROM e_message WHERE chatid = 1 ORDER BY timestamp DESC LIMIT 0, 1' at line 1]
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlState: '42000',
index: 0 }
查询通过console.log()看起来像这样:
INSERT INTO e_message (chatid, message, userid) VALUES(1, 'test123', 1);
SELECT * FROM e_message WHERE chatid = 1 ORDER BY timestamp DESC LIMIT 0, 1;
我不知道这有什么不对……
编辑:
如果我将它分成两个查询,我得到我想要的结果:
Message.save = function(message, callback){
db.query("INSERT INTO e_message (chatid, message, userid) VALUES(" + message.chatid + ", '" + message.message +"', " + message.userid + ");", function(err, rows, fields){
db.query("SELECT * FROM e_message WHERE userid = " + message.userid + " AND chatid = " + message.chatid + " ORDER BY timestamp DESC LIMIT 0, 1;", function(err, rows, filds){
callback(err, new Message(rows[0]));
});
});
}
谢谢!
解决方法:
默认情况下,node-mysql不允许您在单个查询中发出多个SQL语句.
为此,您需要在创建连接时设置multipleStatements连接选项.
请注意,允许这样做可能会使您面临SQL注入的风险,尤其是在将语句构建为字符串时.例如,如果您的message.userid设置为字符串1);删除数据库生成; SELECT(,您将遇到麻烦.
在这种情况下,你真正想要的是插入和第二个SELECT LAST_INSERT_ID()来获取插入最新记录的id.它将返回会话的最新插入的自动增量键,也就是说,它不会受到其他连接/会话的其他插入的影响.
标签:javascript,mysql,node-js,node-mysql 来源: https://codeday.me/bug/20190825/1717719.html