day2

python操作数据库
import pymysql
DATABASE={
'host':'localhost',
'database':'test',
'user':'root',
'password':'123456'
}
# 定义连接对象db
db=pymysql.connect(**DATABASE)
# 定义游标
cursor=db.cursor()
# 查询实现
# sql='select * from student'
# cursor.execute(sql)
# results=cursor.fetchall()
# for row in results:
# print(row)
#其他sql语句实现
sql="DELETE FROM `student` WHERE (`student_id`='4')"
cursor.execute(sql)
db.commit()

数据库操作的回滚操作
db=getConnect()
cursor=db.cursor()
sql1="INSERT INTO `student` (`name`, `age`) VALUES ('pi', '14')"
# 错误sql语句
sql2="INSERT INTO `student` (`name`, `age`) VALUES ('po', 'tu')"
try:
cursor.execute(sql1)
# 获取插入数据返回的id
id1 = db.insert_id()
print("插入ID为: {} 的新数据".format(id1))
cursor.execute(sql2)
id2=db.insert_id()
cursor.close()
db.commit()
except Exception as e:
print("出现错误:",e)
cursor.close()
# 数据库炒作出现错误回滚
db.rollback()
db.close()

捕捉异常
try:
a=[1,2,3]
print(a[4])
except Exception as e:
print(e)

posted on 2019-05-14 16:37  看你妹儿  阅读(79)  评论(0编辑  收藏  举报

导航