Guest User

Untitled

a guest
Nov 4th, 2017
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. #!/usr/bin/python
  2. # - * -coding: utf - 8 - * -
  3.  
  4. """
  5. This very simple CLI application is used to automate process of recreating existing database or creating new one.
  6. It's written in Python 3.6. and it uses MySQLdb library for connection with database.
  7. On start, it asks for credentials. You can just skip inputs (by pressing enter) for default values.
  8. If you don't have MySQLdb package, install it with:
  9. `sudo apt-get install python-pip python-dev libmysqlclient-dev`
  10. """
  11.  
  12. import MySQLdb
  13.  
  14. database_name = input("Database name: \n> ")
  15. database_host = input("Database host: (leave empty for localhost)\n> ")
  16. database_port = input("Database port: (leave empty for 3306) \n> ")
  17. database_user = input("Database user: (leave empty for root)\n> ")
  18. database_pass = input("Database pass: (can be empty)\n> ")
  19.  
  20. if str(database_host).strip() == "":
  21. database_host = "localhost"
  22.  
  23. if str(database_user).strip() == "":
  24. database_user = "root"
  25.  
  26. if str(database_port).strip() == "":
  27. database_port = 3306
  28.  
  29. try:
  30. connection = MySQLdb.connect(host=database_host, port=database_port, user=database_user,passwd=database_pass )
  31.  
  32. except:
  33. print("\nINVALID CREDENTIALS!")
  34. exit(0)
  35.  
  36. cursor = connection.cursor()
  37. sql = f'CREATE DATABASE {database_name}'
  38.  
  39. try:
  40. cursor.execute(sql)
  41. print("Database created!")
  42.  
  43. except:
  44. print("*"*15 + "\nDatabase exist. Override? (y/n)\n")
  45. answer = input("> ")
  46. if answer == "y":
  47. cursor.execute(f"DROP DATABASE {database_name}")
  48. cursor.execute(f"CREATE DATABASE {database_name}")
  49. print("Database recreated!")
  50.  
  51. else:
  52. print("Overriding skipped!")
Add Comment
Please, Sign In to add comment