我正在使用SQL查询来查找所有具有特定RFID值的用户,每个用户可以具有多个RFID值。
我创建了一个准备好的语句,因为插入的值应该只是数字,所以实际上并不需要,但是,即使我仅输入一个存储的值,我仍然收到错误消息Incorrect number of arguments executing prepared statement
在元组中。
可变RFID是函数中的参数
conn = Database.connect() # returns an instance of connector.connect
cursor = conn.cursor(prepared=True) # Creates a cursor that is expecting
sql_query = """SELECT RFID, users.UserID, FirstName, Surname, Email, Dob, Gender, Mobile
FROM users
JOIN RFIDs ON (users.UserID = RFIDs.UserID)
WHERE users.UserID = (SELECT UserID FROM RFIDs WHERE RFID = '%s');"""
cursor.execute(sql_query, (rfid,)) # Get user info
user_info_array = cursor.fetch() # Store the results
conn.commit() # Save the changes to the database
该查询在我使用时以及在其中手动输入值时均能正常工作。
预先感谢
答案 0 :(得分:2)
您不应在%s左右使用单引号
sql_query = """SELECT RFID, users.UserID, FirstName, Surname, Email, Dob, Gender, Mobile
FROM users
JOIN RFIDs ON (users.UserID = RFIDs.UserID)
WHERE users.UserID = (SELECT UserID FROM RFIDs WHERE RFID = %s);"""
并且如spencer7593所建议的,对于子查询,应使用IN子句,而不是=(等于运算符),以避免子查询返回多于一行的错误
sql_query = """SELECT RFID, users.UserID, FirstName, Surname, Email, Dob, Gender, Mobile
FROM users
JOIN RFIDs ON (users.UserID = RFIDs.UserID)
WHERE users.UserID IN (SELECT UserID FROM RFIDs WHERE RFID = %s);"""
或内部联接
sql_query = """SELECT RFID, users.UserID, FirstName, Surname, Email, Dob, Gender, Mobile
FROM users
JOIN RFIDs ON (users.UserID = RFIDs.UserID)
inner join (
SELECT UserID FROM RFIDs WHERE RFID = %s
) t on T.UserID = users.UserID ;"""