我正在使用MySQL和Node JS,我正在检测现有用户是否已经在数据库中。以下代码是我一直在使用的代码:
var username = "RandomUsername";
var email = "RandomEmail@gmail.com";
var sql = "SELECT * FROM users WHERE user_name = " + username + " OR user_email = " + email;
connection.query(sql, function(err, rows, fields) {
if (err) throw err;
if (rows.length !== 0) {
errors.push("Sorry, that email or username already being used.");
}
这是我收到的错误消息:
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 'cameroncjones4'' OR user_email = ''cameroncjones4''' at line 1
at Query.Sequence._packetToError (/Users/CameronJones/Desktop/NodeJS/LoginSystem/node_modules/mysql/lib/protocol/sequences/Sequence.js:48:14)
at Query.ErrorPacket (/Users/CameronJones/Desktop/NodeJS/LoginSystem/node_modules/mysql/lib/protocol/sequences/Query.js:83:18)
at Protocol._parsePacket (/Users/CameronJones/Desktop/NodeJS/LoginSystem/node_modules/mysql/lib/protocol/Protocol.js:271:23)
at Parser.write (/Users/CameronJones/Desktop/NodeJS/LoginSystem/node_modules/mysql/lib/protocol/Parser.js:77:12)
at Protocol.write (/Users/CameronJones/Desktop/NodeJS/LoginSystem/node_modules/mysql/lib/protocol/Protocol.js:39:16)
at Socket.<anonymous> (/Users/CameronJones/Desktop/NodeJS/LoginSystem/node_modules/mysql/lib/Connection.js:96:28)
at Socket.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:163:16)
at Socket.Readable.push (_stream_readable.js:126:10)
at TCP.onread (net.js:538:20)
--------------------
at Protocol._enqueue (/Users/CameronJones/Desktop/NodeJS/LoginSystem/node_modules/mysql/lib/protocol/Protocol.js:135:48)
at Connection.query (/Users/CameronJones/Desktop/NodeJS/LoginSystem/node_modules/mysql/lib/Connection.js:201:25)
at IncomingMessage.<anonymous> (/Users/CameronJones/Desktop/NodeJS/LoginSystem/app.js:86:20)
at IncomingMessage.emit (events.js:107:17)
at IncomingMessage.Readable.read (_stream_readable.js:373:10)
at flow (_stream_readable.js:750:26)
at resume_ (_stream_readable.js:730:3)
at _stream_readable.js:717:7
at process._tickCallback (node.js:355:11)
帮助解决这个问题。
答案 0 :(得分:2)
您需要将'
和;
添加到SQL query
。
试试这个:
var username = "RandomUsername";
var email = "RandomEmail@gmail.com";
var sql = "SELECT * FROM users WHERE user_name = '" + username + "' OR user_email = '" + email + "';";
并且不要忘记每个查询结束时的;
。
编辑:
我创建了一个数据库以重现您的错误,您的错误肯定是引号'
。
尝试将我的代码复制/粘贴到您的代码中,然后让我知道它的结果。当然,你需要一个连接对象,但我认为你已经在使用它了。
var username = "RandomUsername";
var email = "RandomEmail@gmail.com";
var sql = "SELECT * FROM users WHERE user_name = '" + username + "' OR user_email = '" + email+ "'";
connection.connect();
connection.query(sql, function(err, rows, fields) {
if (err) throw err;
if (rows.length !== 0) {
console.log(rows);
connection.end();
}else{
console.log('Nothing match');
}
});
我的猜测是,当你尝试将单引号放入双引号时,因为你的编辑器(atom?sublimeText?)。