tkinter - 格式化字符串中的 Python 3 MySQL sql 语法错误
问题描述
我正在玩 tkinter 和 MySQL,当我尝试从数据库中选择内容时出现错误。我感觉这个错误与我有限的 sql 和/或 tkinter 经验有关......
所以,我有一个 tkinter 按钮调用一个名为“testUserCredentials”的函数:
# Creating the login button, giving it the text "Log In", and
btnLogIn = ttk.Button(self, text="Log In", command=lambda:
testUserCredentials(uNameTb.get(),
pwdTb.get()))
据我了解, .get() 方法获取用户在文本框中输入的文本。然后调用 testUserCredentials(uName, password),在这种情况下,uName 应该等于“AbbieH”,密码应该是“pui8Aifi”。该函数执行以下操作:
def testUserCredentials(uName, password):
query = ("SELECT username, password FROM users WHERE username = %s, password = %s")
args = (uName, password)
sqlResult = sendSqlQuery(query, args)
然后运行我必须处理与 MySQL 数据库通信的函数:
# Function for sending SQL queries to the MySQL database, accepts the query to
# be sent as a string
def sendSqlQuery(query, args):
try:
# Creating the connection string and parsing the details of which server
# User to use, their password, the host for the connector to look at,
# and lastly which database for them
cnx = mysql.connector.connect(user='hireOut',
password='>5/>£7(OW-1Bo>9e',
host='localhost',
database='hireout')
# Creating a cursor to be able to iterate through any results that are
# parsed back from the query
cursor = cnx.cursor()
# Telling the cursor to execute the query string
cursor.execute(query, args)
sqlResult = cursor.fetchall()
for (username, password) in cursor:
print("Username: %s" % username)
print("Password: %s" % password)
return sqlResult
# using .is_connected() to check if the connection was made successfully
if cnx.is_connected():
print("Connection Established")
所以,当我按下登录按钮时,我得到的错误是:
1064 (42000): 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 ', password = 'pui8Aifi'' at line 1
我对 MySQL 语法的理解是 WHERE 语句的字符串必须用单引号括起来,我认为我的字符串应该格式化为:
SELECT username, password FROM users WHERE username = 'AbbieH', password = 'pui8Aifi';
我心中的这个字符串应该没问题,不会抛出错误......但它确实......那么我错过了什么?
提前感谢您的帮助
解决方案
我认为你必须用布尔运算符关键字替换第二个逗号: WHERE username = 'AbbieH' AND password = 'pui8Aifi';