-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPyMySQL-Example.py
More file actions
126 lines (109 loc) · 3.98 KB
/
PyMySQL-Example.py
File metadata and controls
126 lines (109 loc) · 3.98 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import pymysql
# Database connection details
host = "localhost"
user = "your_username"
password = "your_password"
database = "your_database"
# Function to establish a database connection
def connect_to_database():
try:
connection = pymysql.connect(
host=host,
user=user,
password=password,
database=database,
cursorclass=pymysql.cursors.DictCursor
)
print("Connected to the database successfully!")
return connection
except pymysql.Error as e:
print(f"Error connecting to the database: {e}")
return None
# Function to create a table
def create_table(connection):
try:
with connection.cursor() as cursor:
sql = """
CREATE TABLE IF NOT EXISTS employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
position VARCHAR(100) NOT NULL,
salary DECIMAL(10, 2) NOT NULL
)
"""
cursor.execute(sql)
connection.commit()
print("Table 'employees' created successfully!")
except pymysql.Error as e:
print(f"Error creating table: {e}")
# Function to insert data into the table
def insert_data(connection, name, position, salary):
try:
with connection.cursor() as cursor:
sql = "INSERT INTO employees (name, position, salary) VALUES (%s, %s, %s)"
cursor.execute(sql, (name, position, salary))
connection.commit()
print(f"Inserted data for {name} successfully!")
except pymysql.Error as e:
print(f"Error inserting data: {e}")
# Function to query all data from the table
def query_data(connection):
try:
with connection.cursor() as cursor:
sql = "SELECT * FROM employees"
cursor.execute(sql)
results = cursor.fetchall()
print("Employees:")
for row in results:
print(row)
except pymysql.Error as e:
print(f"Error querying data: {e}")
# Function to update data in the table
def update_data(connection, employee_id, new_salary):
try:
with connection.cursor() as cursor:
sql = "UPDATE employees SET salary = %s WHERE id = %s"
cursor.execute(sql, (new_salary, employee_id))
connection.commit()
print(f"Updated salary for employee ID {employee_id} successfully!")
except pymysql.Error as e:
print(f"Error updating data: {e}")
# Function to delete data from the table
def delete_data(connection, employee_id):
try:
with connection.cursor() as cursor:
sql = "DELETE FROM employees WHERE id = %s"
cursor.execute(sql, (employee_id))
connection.commit()
print(f"Deleted employee with ID {employee_id} successfully!")
except pymysql.Error as e:
print(f"Error deleting data: {e}")
# Main function to demonstrate the usage
def main():
# Connect to the database
connection = connect_to_database()
if not connection:
return
try:
# Create the table
create_table(connection)
# Insert some data
insert_data(connection, "John Doe", "Software Engineer", 75000.00)
insert_data(connection, "Jane Smith", "Data Scientist", 85000.00)
# Query and display all data
query_data(connection)
# Update an employee's salary
update_data(connection, 1, 80000.00)
# Query and display all data after update
query_data(connection)
# Delete an employee
delete_data(connection, 2)
# Query and display all data after deletion
query_data(connection)
finally:
# Close the database connection
connection.close()
print("Database connection closed.")
# Run the script
if __name__ == "__main__":
main()