【问题标题】:Check row exists in MySQL through function in python class通过python类中的函数检查MySQL中是否存在行
【发布时间】:2021-07-28 20:42:50
【问题描述】:

我正在尝试在我的数据库管理器类中实现一个函数,该函数检查我的 MySQL 表中是否存在(通过他们的电子邮件)行(用户)。

见下面的代码:

def has_user(self, table_name : str, user_credentials: UserCredentials) -> bool:
        mysql_hasuser_query = """
        SELECT COUNT(1) FROM {t_name} WHERE email = {u_email}
        """.format(t_name=table_name, u_email=user_credentials.email)

        cursor = self.connection.cursor()
        cursor.execute(mysql_hasuser_query)
        if cursor.fetchone()[0]:
            print("User exists in database!")
            return True

我收到以下语法错误mysql.connector.errors.ProgrammingError: 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 '@gmail.com' at line 1

但是,我在 MySQL 查询编辑器中实现了这一点,并且运行良好。我不确定我在这里做错了什么。

【问题讨论】:

    标签: python mysql database


    【解决方案1】:

    您没有在查询中引用电子邮件。但是您应该使用参数而不是将字符串格式化到查询中。

    def has_user(self, table_name : str, user_credentials: UserCredentials) -> bool:
        mysql_hasuser_query = """
        SELECT COUNT(1) FROM {t_name} WHERE email = %s
        """.format(t_name=table_name)
    
        cursor = self.connection.cursor()
        cursor.execute(mysql_hasuser_query, (user_credentials.email,))
        if cursor.fetchone()[0]:
            print("User exists in database!")
            return True
    

    【讨论】:

    • 太好了,我现在明白我做错了什么。非常感谢这按预期工作。
    猜你喜欢
    • 2014-06-24
    • 1970-01-01
    • 2021-05-24
    • 2022-07-06
    • 2016-12-05
    • 2011-06-16
    • 2014-04-10
    • 2016-11-05
    • 1970-01-01
    相关资源
    最近更新 更多