-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbtest.py
41 lines (30 loc) · 986 Bytes
/
dbtest.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
import pymysql
if __name__ == '__main__':
# 1. prepare the SQL query
sql = "select * from todo"
# 2. create the connection
connection = pymysql.connect(user="root", password="",
host="localhost", database="todolist")
# 3. get a cursor
cursor = connection.cursor()
# 4. execute the query
cursor.execute(sql)
# 5. fetch the results (and print them)
result = cursor.fetchall()
print(result)
# 6. close the cursor
cursor.close()
# another SQL query, for inserting elements
sql_insert = "insert into todo(description, urgent) values (%s, %s)"
my_description = "go home"
my_urgency = 1
# get a new cursor
cursor2 = connection.cursor()
# execute the query
cursor2.execute(sql_insert, (my_description, my_urgency))
# commit changes
connection.commit()
# close the cursor
cursor2.close()
# 6a. finally, close the connection
connection.close()