Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- ''' Python3 code that will check for Mysql installation ,
- ******** Target is linux Debian 12 os using python3 *****
- This will via menu auto create a databases named Contacts and
- set up a Contacts table with fields for you and provides a menu to do the following
- Check MySQL installation status
- Create 'Contacts' database
- Create 'Contacts' table
- Add a new contact
- Find contact
- Find and update contact
- Exit
- '''
- '''
- A dam site faster than finding records as Ive seen done over many years
- within business and within government departments Now it takes you a couple of seconds
- to do and not hours , weeks , and months as Ive also seen done
- Far better dont you think and saves one hell of allot of time
- '''
- ''' MD Harrington 11-06-2023 London UK '''
- import subprocess
- import os
- import getpass
- import subprocess
- class MySQLChecker:
- def __init__(self):
- self.installed = self.is_mysql_installed()
- self.username = None
- self.password = None
- os.system("clear")
- def is_mysql_installed(self):
- try:
- # Use the "mysql" command with the "--version" option to check if MySQL is installed
- subprocess.run(["mysql", "--version"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- return True
- except FileNotFoundError:
- return False
- except subprocess.CalledProcessError:
- return False
- def print_status(self):
- if self.installed:
- print("MySQL is installed.")
- else:
- print("MySQL is not installed.")
- def create_database(self):
- if self.installed:
- command = f"mysql -u {self.username} -p{self.password} -e 'CREATE DATABASE IF NOT EXISTS Contacts;'"
- result = subprocess.run(command, shell=True, capture_output=True, text=True)
- if "Contacts" in result.stdout:
- print("Contacts database exists.")
- else:
- print("Contacts database created successfully.")
- else:
- print("MySQL is not installed. Unable to create the database. Please install mysql , mariadb first ")
- def create_table(self):
- if self.installed:
- 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));'"
- result = subprocess.run(command, shell=True, capture_output=True, text=True)
- if result.returncode == 0:
- print("Contacts table created successfully.")
- else:
- print("Error creating the contacts table.")
- else:
- print("MySQL is not installed. Unable to create the table.")
- def add_contact(self):
- if self.installed:
- salutation = input("Enter Salutation eg Mr, Mrs : ")
- name = input("Enter contact name: ")
- surname = input("Enter contact surname: ")
- email = input("Enter contact email: ")
- phone = input("Enter contact phone: ")
- command = f"mysql -u {self.username} -p{self.password} Contacts -e \"INSERT INTO contacts (name, email, phone) VALUES ('{salutation}','{name}', '{surname}','{email}', '{phone}');\""
- result = subprocess.run(command, shell=True, capture_output=True, text=True)
- if result.returncode == 0:
- print("Contact added successfully.")
- else:
- print("Error adding the contact.")
- else:
- print("MySQL is not installed. Unable to add the contact.")
- @staticmethod
- def display_menu():
- print("MySQL Menu")
- print("1. Check MySQL installation status")
- print("2. Create 'Contacts' database")
- print("3. Create 'Contacts' table")
- print("4. Add a new contact")
- print("5. Find contact")
- print("6. Find and update contact")
- print("7. Exit")
- def set_credentials(self):
- self.username = input("Enter MySQL username: ")
- self.password = getpass.getpass("Enter MySQL password: ")
- def find_contact(self):
- if self.installed:
- search_term = input("Enter search term (name, surname, phone, or email): ")
- search_value = input("Enter search value: ")
- command = f"mysql -u {self.username} -p{self.password} Contacts -e \"USE Contacts; SELECT * FROM contacts WHERE {search_term} = '{search_value}';\""
- result = subprocess.run(command, shell=True, capture_output=True, text=True)
- if result.returncode == 0:
- search_results = result.stdout.strip().split("\n")
- if len(search_results) > 1:
- print("Search results:")
- for row in search_results[1:]:
- print(row)
- select = input("Please use enter key to go back to menu ")
- os.system("clear")
- else:
- print("No matching contacts found.")
- else:
- print("Error executing the search query.")
- def find_and_update_contact(self):
- if self.installed:
- search_term = input("Enter search term (name, surname, phone, or email): ")
- search_value = input("Enter search value: ")
- command = f"mysql -u {self.username} -p{self.password} Contacts -e \"USE Contacts; SELECT * FROM contacts WHERE {search_term} = '{search_value}';\""
- result = subprocess.run(command, shell=True, capture_output=True, text=True)
- if result.returncode == 0:
- search_results = result.stdout.strip().split("\n")
- if len(search_results) > 1:
- print("Search results:")
- for row in search_results[1:]:
- print(row)
- record_id = input("Enter the ID of the record to update: ")
- field_name = input("Enter the name of the field to update (name, surname, email, phone): ")
- new_value = input("Enter the new value: ")
- update_command = f"mysql -u {self.username} -p{self.password} Contacts -e \"UPDATE contacts SET {field_name} = '{new_value}' WHERE id = {record_id};\""
- update_result = subprocess.run(update_command, shell=True, capture_output=True, text=True)
- if update_result.returncode == 0:
- print("Record updated successfully.")
- else:
- print("Error updating the record.")
- else:
- print("No matching contacts found.")
- else:
- print("Error executing the search query.")
- else:
- print("MySQL is not installed. Unable to perform the search and update.")
- def main():
- mysqlchecker = MySQLChecker()
- ''' get user name and password for mysql db , mariadb '''
- mysqlchecker.set_credentials()
- choice = 0
- while choice != 4:
- mysqlchecker.display_menu()
- choice = int(input("Enter your choice: "))
- if choice == 1:
- mysqlchecker.print_status()
- elif choice == 2:
- mysqlchecker.create_database()
- elif choice == 3:
- mysqlchecker.create_table()
- elif choice == 4:
- mysqlchecker.add_contact()
- elif choice == 5:
- mysqlchecker.find_contact()
- elif choice == 6:
- mysqlchecker.find_and_update_contact()
- elif choice == 7:
- print("Exiting... Thank you for using mysql , Maria DB")
- os.system("clear")
- exit()
- else:
- print("Invalid choice. Please try again.")
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement