我在执行节点mysql2
模块的更新查询时遇到了一些问题。我正在使用'?'准备查询占位符,然后像这样传递值;执行UPDATE时出错
socket.on('connection', function(client){
[...]
client.on('userjoin', function(username, userid){
run_db_insert("UPDATE users_table SET clientid = ? WHERE user = ?", [client.id, userid], function(){
console.log(client.id + ' <=> ' + userid);
});
[...]
});
不幸的是,这引发了一个错误; 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 ''12345678' WHERE userid = ?' at line 1
数据未反映在数据库中。出于某种原因,代码似乎没有选取第二个问号占位符,因此它没有传递正确的值(即它试图找到的?
)。
如果我将代码更改为此;
run_db_insert("UPDATE users_table SET clientid = ? WHERE user = '" + userid + "'", [client.id], function(){
...然后更新运行没有错误,并反映在数据库中。如果我console.log
client.id
和userid
,控制台正确地反映这些值。
我的run_db_insert
功能如下;
function run_db_insert(sql, args, callback){
var mysql = svc_mysql2.createConnection({
// connection details
});
mysql.connect(function(err){
if(err){
console.log('Error connecting to DB: ' + err);
}
});
mysql.query(sql, [args], function(err){
if (err){
console.log(err);
return;
}
callback();
});
mysql.end();
};
我没有问题使用多个'?'执行SELECT或INSERT查询。占位符(具有稍微修改的函数,该函数的第11行中有result
,然后在回调中返回),但是我发现UPDATE没有正确地分配所有传递给它的参数。
不要使用字符串连接,你会很容易受到SQL注入。 –
'...靠近''12345678'where userid =?'在第1行......'这看起来像客户端ID被作为一个字符串传递。它(clientid字段)是一个字符串吗? – abl
@abl'userid'是一个varchar,因为它是唯一索引,而'clientid'是DB中的文本。这两个值都在代码中作为字符串处理。 @grasGendarme我明白这就是为什么我打算找到一个准备好的解决方案:) –