Advertisement
Mark2020H

Python 3 script that creates a database and contacts table for you Checks mysql install

Jun 11th, 2023 (edited)
1,360
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.15 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. ''' Python3 code that will  check for Mysql installation ,
  4. ********  Target is linux Debian 12  os using python3  *****
  5. This will via menu auto create a databases named Contacts and
  6. set up a Contacts table with fields for you and provides a menu to  do the following
  7.  
  8. Check MySQL installation status
  9.  
  10. Create 'Contacts' database
  11. Create 'Contacts' table
  12. Add a new contact
  13. Find contact
  14. Find and update contact
  15. Exit
  16.  
  17. '''
  18.  
  19. '''
  20.  
  21. A dam site  faster than finding records  as Ive seen done over many years  
  22. within business and  within government departments  Now it takes  you a  couple of seconds
  23. to do  and not hours , weeks , and  months  as Ive also seen done
  24. Far better dont you think and saves one hell of allot of time
  25.  
  26.  
  27. '''
  28.  
  29. '''  MD Harrington 11-06-2023  London UK '''
  30.  
  31. import subprocess
  32. import os
  33. import getpass
  34.  
  35.  
  36. import subprocess
  37.  
  38. class MySQLChecker:
  39.     def __init__(self):
  40.         self.installed = self.is_mysql_installed()
  41.         self.username = None
  42.         self.password = None
  43.         os.system("clear")
  44.        
  45.  
  46.     def is_mysql_installed(self):
  47.         try:
  48.             # Use the "mysql" command with the "--version" option to check if MySQL is installed
  49.             subprocess.run(["mysql", "--version"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  50.             return True
  51.         except FileNotFoundError:
  52.             return False
  53.         except subprocess.CalledProcessError:
  54.             return False
  55.  
  56.     def print_status(self):
  57.         if self.installed:
  58.             print("MySQL is installed.")
  59.         else:
  60.             print("MySQL is not installed.")
  61.  
  62.     def create_database(self):
  63.         if self.installed:
  64.            
  65.  
  66.             command = f"mysql -u {self.username} -p{self.password} -e 'CREATE DATABASE IF NOT EXISTS Contacts;'"
  67.             result = subprocess.run(command, shell=True, capture_output=True, text=True)
  68.  
  69.  
  70.             if "Contacts" in result.stdout:
  71.                 print("Contacts database exists.")
  72.             else:
  73.                 print("Contacts database created successfully.")
  74.         else:
  75.             print("MySQL is not installed. Unable to create the database. Please install mysql , mariadb first ")
  76.  
  77.     def create_table(self):
  78.         if self.installed:
  79.            
  80.  
  81.             command = f"mysql -u {self.username} -p{self.password} Contacts -e 'CREATE TABLE IF NOT EXISTS contacts (id INT AUTO_INCREMENT PRIMARY KEY, salutation VARCHAR(20),  name VARCHAR(20), surname VARCHAR(20), email VARCHAR(40), phone VARCHAR(20));'"
  82.             result = subprocess.run(command, shell=True, capture_output=True, text=True)
  83.  
  84.             if result.returncode == 0:
  85.                 print("Contacts table created successfully.")
  86.             else:
  87.                 print("Error creating the contacts table.")
  88.         else:
  89.             print("MySQL is not installed. Unable to create the table.")
  90.  
  91.     def add_contact(self):
  92.         if self.installed:
  93.            
  94.  
  95.             salutation       =     input("Enter Salutation eg Mr, Mrs : ")
  96.             name        =     input("Enter contact name: ")
  97.             surname     =     input("Enter contact surname: ")
  98.             email       =     input("Enter contact email: ")
  99.             phone       =     input("Enter contact phone: ")
  100.  
  101.  
  102.             command = f"mysql -u {self.username} -p{self.password} Contacts -e \"INSERT INTO contacts (name, email, phone) VALUES ('{salutation}','{name}', '{surname}','{email}', '{phone}');\""
  103.             result = subprocess.run(command, shell=True, capture_output=True, text=True)
  104.  
  105.             if result.returncode == 0:
  106.                 print("Contact added successfully.")
  107.             else:
  108.                 print("Error adding the contact.")
  109.         else:
  110.             print("MySQL is not installed. Unable to add the contact.")
  111.  
  112.     @staticmethod
  113.  
  114.     def display_menu():
  115.        
  116.         print("MySQL Menu")
  117.         print("1. Check MySQL installation status")
  118.         print("2. Create 'Contacts' database")
  119.         print("3. Create 'Contacts' table")
  120.         print("4. Add a new contact")
  121.         print("5. Find contact")
  122.         print("6. Find  and update contact")
  123.         print("7. Exit")
  124.  
  125.     def set_credentials(self):
  126.         self.username = input("Enter MySQL username: ")
  127.         self.password = getpass.getpass("Enter MySQL password: ")
  128.  
  129.     def find_contact(self):
  130.  
  131.         if self.installed:
  132.            
  133.  
  134.             search_term = input("Enter search term (name, surname, phone, or email): ")
  135.             search_value = input("Enter search value: ")
  136.  
  137.             command = f"mysql -u {self.username} -p{self.password} Contacts -e  \"USE Contacts; SELECT * FROM contacts WHERE {search_term} = '{search_value}';\""
  138.             result = subprocess.run(command, shell=True, capture_output=True, text=True)
  139.  
  140.             if result.returncode == 0:
  141.                 search_results = result.stdout.strip().split("\n")
  142.                 if len(search_results) > 1:
  143.                     print("Search results:")
  144.                    
  145.                    
  146.                 for row in search_results[1:]:
  147.                     print(row)
  148.                 select = input("Please use enter key to go back to menu ")
  149.                 os.system("clear")
  150.  
  151.                
  152.             else:
  153.                 print("No matching contacts found.")
  154.         else:
  155.             print("Error executing the search query.")
  156.  
  157.     def find_and_update_contact(self):
  158.         if self.installed:
  159.            
  160.             search_term = input("Enter search term (name, surname, phone, or email): ")
  161.             search_value = input("Enter search value: ")
  162.  
  163.             command = f"mysql -u {self.username} -p{self.password} Contacts -e \"USE Contacts; SELECT * FROM contacts WHERE {search_term} = '{search_value}';\""
  164.             result = subprocess.run(command, shell=True, capture_output=True, text=True)
  165.  
  166.             if result.returncode == 0:
  167.                 search_results = result.stdout.strip().split("\n")
  168.                 if len(search_results) > 1:
  169.                     print("Search results:")
  170.                     for row in search_results[1:]:
  171.                         print(row)
  172.                    
  173.                     record_id = input("Enter the ID of the record to update: ")
  174.                     field_name = input("Enter the name of the field to update (name, surname, email, phone): ")
  175.                     new_value = input("Enter the new value: ")
  176.  
  177.                     update_command = f"mysql -u {self.username} -p{self.password} Contacts -e \"UPDATE contacts SET {field_name} = '{new_value}' WHERE id = {record_id};\""
  178.                     update_result = subprocess.run(update_command, shell=True, capture_output=True, text=True)
  179.  
  180.                     if update_result.returncode == 0:
  181.                         print("Record updated successfully.")
  182.                     else:
  183.                         print("Error updating the record.")
  184.                 else:
  185.                     print("No matching contacts found.")
  186.             else:
  187.                 print("Error executing the search query.")
  188.         else:
  189.             print("MySQL is not installed. Unable to perform the search and update.")
  190.        
  191.  
  192.  
  193.  
  194.  
  195. def main():
  196.     mysqlchecker = MySQLChecker()
  197.  
  198.     ''' get user name and password for  mysql db , mariadb '''
  199.     mysqlchecker.set_credentials()
  200.  
  201.  
  202.     choice = 0
  203.  
  204.     while choice != 4:
  205.         mysqlchecker.display_menu()
  206.         choice = int(input("Enter your choice: "))
  207.  
  208.         if choice == 1:
  209.             mysqlchecker.print_status()
  210.         elif choice == 2:
  211.             mysqlchecker.create_database()
  212.         elif choice == 3:
  213.             mysqlchecker.create_table()
  214.         elif choice == 4:
  215.             mysqlchecker.add_contact()
  216.         elif choice == 5:
  217.             mysqlchecker.find_contact()
  218.         elif choice == 6:
  219.             mysqlchecker.find_and_update_contact()
  220.         elif choice == 7:
  221.             print("Exiting... Thank you for using mysql , Maria DB")
  222.             os.system("clear")
  223.             exit()
  224.         else:
  225.             print("Invalid choice. Please try again.")
  226.  
  227.  
  228.  
  229.  
  230. if __name__ == '__main__':
  231.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement