-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql_demo.py
More file actions
78 lines (65 loc) · 2.23 KB
/
sql_demo.py
File metadata and controls
78 lines (65 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import pymysql
# Function to create a connection to the MySQL database
def create_connection():
return pymysql.connect(
host="container_ip_address", # MySQL server host in another container
user="root", # MySQL username
password="root", # MySQL password decared in container
database="userinfo" # MySQL database name declared in container
)
# Function to create a table to store usernames if it doesn't exist
def create_table(connection):
cursor = connection.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS usernames (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255)
)
""")
connection.commit()
cursor.close()
# Function to insert a name into the database
def insert_name(connection, name):
cursor = connection.cursor()
cursor.execute("INSERT INTO usernames (name) VALUES (%s)", (name,))
connection.commit()
cursor.close()
#Insert name into files also
with open("servers.txt", "a") as file:
file.write(name+"\n")
# Function to fetch all usernames from the database
def fetch_all_usernames(connection):
cursor = connection.cursor()
cursor.execute("SELECT name FROM usernames")
usernames = [row[0] for row in cursor.fetchall()]
cursor.close()
return usernames
# Main function
def main():
connection = create_connection()
create_table(connection)
while True:
print("1. Add a name")
print("2. Show all usernames")
print("3. Quit")
choice = input("Enter your choice: ")
if choice == "1":
name = input("Enter a name: ")
insert_name(connection, name)
print(f"Name '{name}' added to the database.")
elif choice == "2":
usernames = fetch_all_usernames(connection)
if usernames:
print("usernames in the database:")
for name in usernames:
print(name)
else:
print("No usernames found in the database.")
elif choice == "3":
print("Goodbye!")
break
else:
print("Invalid choice. Please try again.")
connection.close()
if __name__ == "__main__":
main()