Table of contents
1. Instructions for using the pymysql module
1. Instructions for using the pymysql module
1.1 Operation process
import pymysql
conn = pymysql.connect(parameter list)
Connection object operation instructions:
conn.close()
conn.commit()
conn.rollback()
1.2 Get the cursor object
cur = conn.cursor()
Cursor operation instructions:
execute(operation [parameters]): Use the cursor to execute the SQL statement and return the number of affected rows, mainly used to execute insert, update, delete, select and other statements. You can also execute creater, alter, drop and other statements.
cur.fetchone(): Get a piece of data in the query result set and return a tuple
curfetchall(): Get all the data in the query result set and return a tuple
cur.close(): Close the cursor, indicating that the operation with the database is complete
2. Examples
Get a piece of data
import pymysql
conn = pymysql.connect(host="localhost",
port=3306,
user="root",
password="123456",
database="gctzsc_db",
charset="utf8"
)
cursor = conn.cursor()
sql = "select * from type_tb;"
cursor.execute(sql)
row = cursor.fetchone()
print(row)
cursor.close()
conn.close()
Get multiple pieces of data
import pymysql
conn = pymysql.connect(host="localhost",
port=3306,
user="root",
password="123456",
database="gctzsc_db",
charset="utf8"
)
cursor = conn.cursor()
sql = "select * from type_tb;"
cursor.execute(sql)
row = cursor.fetchall()
print(row)
cursor.close()
conn.close()
Add, delete, modify and query data
import pymysql
conn = pymysql.connect(host="localhost",
port=3306,
user="root",
password="123456",
database="gctzsc_db",
charset="utf8"
)
cursor = conn.cursor()
sql = "update type_tb set t_name = '其它' where t_id = '11';"
try:
cursor.execute(sql)
conn.commit()
except:
conn.rollback()
sql = "select * from type_tb where t_id = '11';"
cursor.execute(sql)
row = cursor.fetchone()
print(row)
cursor.close()
conn.close()