python通过pymysql提供的接口完成数据的读写,通过try-except进行异常捕捉,并配合commit、rollback完成一系列有效操作。
import pymysql
# 1.创建数据库连接对象
conn = pymysql.connect(host="localhost",user="root",passwd="123456",db="MOSHOU",charset="utf8")
# 2.创建游标对象
cur = conn.cursor()
# 3.利用游标对象的execute方法执行sql语句
sql_insert = "insert into hero values(20,'瓦煲饭','男','卡死');")
cur.execute(sql_insert)
# 4.提交到数据库执行
conn.commit()
# 5.关闭游标
cur.close()
# 6.关闭数据库连接
conn.close()
import pymysql
# connect参数简写
db = pymysql.connect("localhost","root","123456","MOSHOU",charset="utf8")
cur = db.cursor()
try:
sql_select="select * from hero;"
cur.execute(sql_select) #所有查询结果都在cur对象里
data = cur.fetchone()
print(data)
print("************************")
data2 = cur.fetchmany(3)
for i in data2:
print(i)
print("************************")
data3 = cur.fetchall()
for i in data3:
print(i)
print("************************")
print("ok")
db.commit()
except Exception as e:
print(e)
人工智能(mysql)—— 目录汇总