查询
import pymysql
conn = pymysql.Connect(host='127.0.0.1',port=3306,user='root',passwd='123456',db='ResearchPlatform',charset='utf8')
cursor = conn.cursor()
sql = "select * from Query"
cursor.execute(sql)
print('行数:',cursor.rowcount)
# 获取一条记录
# rs = cursor.fetchone()
# print('获取一条记录:',rs)
# 获取指定条数记录
# for each in cursor.fetchmany(2):
# print(each)
# 获取全部记录
# for i in cursor.fetchall():
# print(i)
增删改
涉及到事务提交和回滚操作
import pymysql
conn = pymysql.Connect(host='127.0.0.1',port=3306,user='root',passwd='123456',db='ResearchPlatform',charset='utf8')
conn.autocommit(False) #不自动提交事务
cursor = conn.cursor()
# 增删改
# sqlInsert = "insert into Query values('1215', 1, 'bbb', '1111', '222', 1)"
# sqlUpdate = "update Query set Name='name41' where QueryID='1212'"
sqlDelete = "delete from Query where QueryID='1213'"
try:
# cursor.execute(sqlInsert)
# print(cursor.rowcount)
# cursor.execute(sqlUpdate)
# print(cursor.rowcount)
cursor.execute(sqlDelete)
print(cursor.rowcount)
conn.commit() # 提交事务
except Exception as e:
print("Reason:", e)
conn.rollback() # 回滚事务
cursor.close()
conn.close()