Last active
March 23, 2022 14:54
-
-
Save milosb793/68ded5558adffa7932174a34b900d31a to your computer and use it in GitHub Desktop.
Interactive Python script used to automate (re)creation of database using MySQL (MariaDB)
This file contains 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 python | |
# - * -coding: utf - 8 - * - | |
""" | |
This very simple CLI application is used to automate process of recreating existing database or creating new one. | |
It's written in Python 3.6. and it uses MySQLdb library for connection with database. | |
On start, it asks for credentials. You can just skip inputs (by pressing enter) for default values. | |
If you don't have MySQLdb package, install it with: | |
`sudo apt-get install python-pip python-dev libmysqlclient-dev python3-mysqldb` | |
""" | |
import MySQLdb | |
database_name = input("Database name: \n> ") | |
database_host = input("Database host: (leave empty for localhost)\n> ") | |
database_port = input("Database port: (leave empty for 3306) \n> ") | |
database_user = input("Database user: (leave empty for root)\n> ") | |
database_pass = input("Database pass: (can be empty)\n> ") | |
if str(database_host).strip() == "": | |
database_host = "localhost" | |
if str(database_user).strip() == "": | |
database_user = "root" | |
if str(database_port).strip() == "": | |
database_port = 3306 | |
try: | |
connection = MySQLdb.connect(host=database_host, port=database_port, user=database_user,passwd=database_pass ) | |
except: | |
print("\nINVALID CREDENTIALS!") | |
exit(0) | |
cursor = connection.cursor() | |
sql = f'CREATE DATABASE {database_name}' | |
try: | |
cursor.execute(sql) | |
print("Database created!") | |
except: | |
print("*"*15 + "\nDatabase exist. Override? (y/n)\n") | |
answer = input("> ") | |
if answer == "y": | |
cursor.execute(f"DROP DATABASE {database_name}") | |
cursor.execute(f"CREATE DATABASE {database_name}") | |
print("Database recreated!") | |
else: | |
print("Overriding skipped!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment