给定特定输出时如何触发“返回”

时间:2019-07-18 12:41:45

标签: python pymysql

我正在用Python开发认证脚本。我需要PyMySQL来检查用户是否存在,该怎么办?

我阅读了文档,但没有找到问题的答案。

def check():
    connection = pymysql.connect(host='localhost',
                        user='user',
                        password='passwd',
                        db='db',
                        charset='utf8mb4',
                        cursorclass=pymysql.cursors.DictCursor)

    userexist = # PyMySQL check code here
    if userexist=='True':
       return 'good'

1 个答案:

答案 0 :(得分:0)

不清楚是要检查pymysql用户还是要从数据库中检查用户。此代码将解决这两个实例。 pymysql将引发异常:pymysql.err.OperationalError(如果用户不存在)。因此,您需要尝试一下,除了这样的子句:

def check():
    try:
        connection = pymysql.connect(host='localhost',
                                     user='user',
                                     password='passwd',
                                     db='db',
                                     charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)
    except pymysql.err.OperationalError:
        print('User with entered connection credentials does not exists')
        return False
    try:
        with connection.cursor() as cursor:
            cursor.execute("select...") # Fill with your select statement
            result = cursor.fetchone()
            if result is None:
                connection.close()
                return False
    finally:
        connection.close()
    return 'good'