【问题标题】:Why is fetchone() returning none here? [duplicate]为什么 fetchone() 在这里没有返回? [复制]
【发布时间】:2020-09-30 22:36:09
【问题描述】:

为什么调用 onLogin() 时 fetchone() 返回 None ,即使数据库有一行有值? 当我在 sql 数据库中使用相同的查询时,它返回正确的值。 使用 fetchall() 并使用 for 循环在终端上不会返回任何内容。

import mysql.connector
#SQL CONNECTION
db = mysql.connector.connect(
    host="localhost",
    user="root",
    password="",
    database="python"
)
cursor = db.cursor(buffered=True)


#main
def onStart():
    global username
    print("Enter a username to continue")
    username = input()
    #Checking the database for the username
    query = "SELECT username FROM userdata"
    cursor.execute(query)
    result = cursor.fetchall()
    for x in result:
        if x == (username,):
            onLogin()
        else:
            print("Error Occurred!")
def onLogin():
    print("Enter a password")
    password = input()
    #comparing pwds
    query = "SELECT password FROM userdata WHERE username = '%s'"
    cursor.execute(query, username)
    result = cursor.fetchone()
    print(result)
onStart()

【问题讨论】:

  • 你不能引用占位符(%s,而不是'%s')。您必须将值的元组传递给execute,而不是单个值。
  • @deceze username 在这里是全局变量,所以它可以工作,通过在onLogin 中使用print(username) 进行检查,使用%s 而不是'%s' 给出语法错误。你能举例说明如何正确地将用户名作为元组传递吗?

标签: python mysql


【解决方案1】:

正如 deceze 所说,您不应在准备好的查询中引用 '%s' 占位符。

此外,您应该避免在数据库中获取每个用户,只是为了弄清楚这个用户是否存在 - 当您使用它时,您可以在同一个查询中获取密码并在您的程序中进行比较。 (当然,在现实生活中,您会使用密码派生函数,而不是将明文密码存储在数据库中。)

import mysql.connector

# SQL CONNECTION
db = mysql.connector.connect(
    host="localhost", user="root", password="", database="python"
)
cursor = db.cursor(buffered=True)


def authenticate():
    username = input("Enter a username to continue")

    cursor.execute(
        "SELECT username, password FROM userdata WHERE username = %s LIMIT 1",
        (username,),
    )
    result = cursor.fetchone()
    if not result:
        print("No such user.")
        return None

    username, correct_password = result
    password = input("Enter a password")
    if password == correct_password:
        print("Access granted!")
    return username

username = authenticate()
# If `username` is none, authentication failed

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 2012-01-30
    相关资源
    最近更新 更多