如何使用python检查用户是否存在

时间:2018-07-10 23:37:58

标签: python-3.x

我有一个查询,例如

def create_db_and_admin(self):
        mysql_server = mysql.connect(host=self.db_server, user="root", passwd="password")
        cursor = mysql_server.cursor()
try:
            create_new_db = f"CREATE DATABASE {self.db}"
            cursor.execute(create_new_db)
        except Exception as e:
            print("Cant create a db")
            print(e)
            sys.exit()
        try:
            create_new_admin_user = f"CREATE USER '{self.db_admusr}'@'%' IDENTIFIED BY '{self.db_adm_passwd}'"
except Exception as e:
            print("User already exists")
            print(e)
            ad_user_admin_rights = f"GRANT ALL PRIVILEGES ON {self.db_name}.* TO '{self.db_admusr}'@'%'"

我想检查用户是否存在,那么我将通过授予选项而不是创建用户。有人可以提出一些想法吗?

1 个答案:

答案 0 :(得分:1)

为什么不这样做

CREATE USER IF NOT EXISTS 'user'@'%' IDENTIFIED BY 'password';

然后授予权限

GRANT ALL PRIVILEGES ON {self.db_name}.* TO '{self.db_admusr}'@'%'

您的代码将类似于

def create_db_and_admin(self):
    mysql_server = mysql.connect(host=self.db_server, user="root", passwd="password")
    cursor = mysql_server.cursor()
    try:
        create_new_db = f"CREATE DATABASE {self.db}"
        cursor.execute(create_new_db)
    except Exception as e:
        print("Cant create a db")
        print(e)
        sys.exit()
    create_new_admin_user = f"CREATE USER IF NOT EXISTS '{self.db_admusr}'@'%' IDENTIFIED BY '{self.db_adm_passwd}'"
    ad_user_admin_rights = f"GRANT ALL PRIVILEGES ON {self.db_name}.* TO '{self.db_admusr}'@'%'"