· 2 years ago · Jun 11, 2023, 07:00 PM
1#!/usr/bin/env python3
2
3''' Python3 code that will check for Mysql installation ,
4******** Target is linux Debian 12 os using python3 *****
5This will via menu auto create a databases named Contacts and
6set up a Contacts table with fields for you and provides a menu to do the following
7
8Check MySQL installation status
9
10Create 'Contacts' database
11Create 'Contacts' table
12Add a new contact
13Find contact
14Find and update contact
15Exit
16
17'''
18
19'''
20
21A dam site faster than finding records as Ive seen done over many years
22within business and within government departments Now it takes you a couple of seconds
23to do and not hours , weeks , and months as Ive also seen done
24Far 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
31import subprocess
32import os
33import getpass
34
35
36import subprocess
37
38class 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
195def 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
230if __name__ == '__main__':
231 main()