格式化字符串中的Python 3 MySQL sql语法错误

时间:2019-01-18 13:05:59

标签: tkinter python-3.7 mysql-8.0

我正在玩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';

在我看来,此字符串应该是正确的,并且不会引发错误...但是可以... 那我想念什么?

在此先感谢您的帮助

1 个答案:

答案 0 :(得分:0)

我认为您必须用布尔运算符关键字替换第二个逗号: 用户名='AbbieH'和密码='pui8Aifi';