-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmysql.py
More file actions
82 lines (72 loc) · 2.16 KB
/
Copy pathmysql.py
File metadata and controls
82 lines (72 loc) · 2.16 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
79
80
81
82
import mysql.connector
from mysql.connector import Error
def create_connection(host_name, user_name, user_password, db_name=None):
"""
Establish a connection to the MySQL database.
"""
connection = None
try:
connection = mysql.connector.connect(
host=host_name,
user=user_name,
passwd=user_password,
database=db_name
)
if connection.is_connected():
print("✅ Connection to MySQL was successful.")
except Error as e:
print(f"❌ The error '{e}' occurred")
return connection
def execute_query(connection, query):
"""
Execute a single SQL query.
"""
cursor = connection.cursor()
try:
cursor.execute(query)
connection.commit()
print("✅ Query executed successfully.")
except Error as e:
print(f"❌ The error '{e}' occurred")
def fetch_query_results(connection, query):
"""
Fetch results from a SELECT query.
"""
cursor = connection.cursor()
result = None
try:
cursor.execute(query)
result = cursor.fetchall()
return result
except Error as e:
print(f"❌ The error '{e}' occurred")
return result
if __name__ == "__main__":
# Update with your MySQL credentials
host = "localhost"
user = "root"
password = "your_password"
database = "test_db"
# Create a connection
conn = create_connection(host, user, password, database)
if conn:
# Example: Create a table
create_table_query = """
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
age INT,
PRIMARY KEY (id)
);
"""
execute_query(conn, create_table_query)
# Example: Insert data
insert_query = "INSERT INTO users (name, age) VALUES ('Alice', 25);"
execute_query(conn, insert_query)
# Example: Fetch data
select_query = "SELECT * FROM users;"
results = fetch_query_results(conn, select_query)
for row in results:
print(row)
conn.close()
print("🔒 Connection closed.")