1

I have a query such as

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}'@'%'"

I want to check if the user exists then I will just pass grant option rather than creating the user. Can someone suggest some ideas...

Roxy
  • 127
  • 1
  • 7

1 Answers1

1

Why not do this instead

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

and then grant permissions

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

Your code will look something like

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}'@'%'"
lakshayg
  • 2,053
  • 2
  • 20
  • 34
  • Thanks I tried that but the only issue is I am trying random password and even if the user exists, it generates password for that – Roxy Jul 10 '18 at 23:54
  • Try this: `SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = 'username')` (Source: https://stackoverflow.com/a/3049942/3033441) – lakshayg Jul 11 '18 at 00:06