Last active
April 26, 2017 20:44
-
-
Save felds/e570ea88c86c3438ea87ad255025c017 to your computer and use it in GitHub Desktop.
Create mysql db and user
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| import MySQLdb | |
| from getpass import getpass | |
| def get_connection(): | |
| while True: | |
| passwd = getpass("Enter root password:") | |
| try: | |
| return MySQLdb.connect("localhost", "root", passwd, "mysql") | |
| except: | |
| print("Invalid password.") | |
| def get_user(c): | |
| while True: | |
| user = input("Enter the user name: ").strip() | |
| num_rows = c.execute("SELECT 1 FROM user WHERE user = %(user)s", { 'user': user }) | |
| if num_rows > 0: | |
| print("This user already exists. Try again.") | |
| else: | |
| return user | |
| def get_schema(default): | |
| return input("Enter the schema name (default: {}): ".format(default)).strip() or default | |
| def get_passwd(): | |
| while True: | |
| passwd = getpass("Enter the password for the new user") | |
| if not passwd: | |
| print("Invalid password.") | |
| else: | |
| return passwd | |
| if __name__ == "__main__": | |
| conn = get_connection() | |
| c = conn.cursor() | |
| user = get_user(c) | |
| schema = get_schema(default=user) | |
| passwd = get_passwd() | |
| sql = """ | |
| CREATE SCHEMA IF NOT EXISTS {0} | |
| DEFAULT CHARACTER SET = utf8mb4 | |
| DEFAULT COLLATE = utf8mb4_general_ci | |
| ; | |
| CREATE USER %(user)s@'localhost' IDENTIFIED BY %(passwd)s; | |
| GRANT ALL PRIVILEGES ON {0}.* TO %(user)s@'localhost'; | |
| FLUSH PRIVILEGES; | |
| """.format(schema) | |
| success = c.execute(sql, locals()) | |
| print("-") | |
| if success: | |
| print("The user/schema pair was created!") | |
| else: | |
| print("There was an error... :(") | |
| conn.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment