python pymysql 模块操作MySQL

查询

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()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值