-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysql_example.py
126 lines (110 loc) · 2.97 KB
/
mysql_example.py
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
host = "localhost"
dbname = "django-db"
user = "root"
password = ""
def createTable():
conn = pymysql.connect(
host=host,
user=user,
password=password,
database=dbname)
# create table operation
try:
with conn.cursor() as curs:
drop_query = "DROP TABLE IF EXISTS users;"
curs.execute(drop_query)
create_query = """
CREATE TABLE IF NOT EXISTS users(
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255),
password VARCHAR(255),
is_admin INT
);
"""
curs.execute(create_query)
conn.commit()
print("Table created successfully!")
except Exception as e:
print(str(e))
finally:
conn.close()
def insertData():
conn = pymysql.connect(
host=host,
user=user,
password=password,
database=dbname)
# insert operation
try:
with conn.cursor() as curs:
insert_query = "INSERT INTO users (username, password, is_admin) VALUES (%s, %s, %s)"
values = ("admin", "admin123", 1)
curs.execute(insert_query, values)
conn.commit()
print("Data inserted successfully!")
except Exception as e:
print(str(e))
finally:
conn.close()
def readData():
conn = pymysql.connect(
host=host,
user=user,
password=password,
database=dbname)
# select operation
try:
with conn.cursor(pymysql.cursors.DictCursor) as curs:
select_query = "SELECT * FROM users"
curs.execute(select_query)
result = curs.fetchall()
for row in result:
print(row['username'])
print(row['password'])
except Exception as e:
print(str(e))
finally:
conn.close()
def updateData():
conn = pymysql.connect(
host=host,
user=user,
password=password,
database=dbname)
# update operation
try:
with conn.cursor() as curs:
update_query = "UPDATE users SET password = %s WHERE username = %s"
values = ("newpassword", "admin")
curs.execute(update_query, values)
conn.commit()
print("Data updated successfully!")
except Exception as e:
print(str(e))
finally:
conn.close()
def deleteData():
conn = pymysql.connect(
host=host,
user=user,
password=password,
database=dbname)
# delete operation
try:
with conn.cursor() as curs:
delete_query = "DELETE FROM users WHERE username = %s"
values = ("admin",)
curs.execute(delete_query, values)
conn.commit()
print("Data deleted successfully!")
except Exception as e:
print(str(e))
finally:
conn.close()
if __name__ == "__main__":
createTable()
insertData()
readData()
updateData()
deleteData()