一、添加方法
db = pymysql.connect(host='localhost',user='root',password='123456',db='python')
cursor = db.cursor()
sql ="""
insert into EMPLOYEE
VALUES
('3','张','天爱',35,'F',8000)
"""
try:
cursor.execute(sql)
db.commit() #提交后,数据才会变
except:
db.rollback()#数据异常时,回滚
db.close()
结果
二、修改
db = pymysql.connect(host='localhost',user='root',password='123456',db='python')
cursor = db.cursor()
sql ="""
update EMPLOYEE set INCOME=18000 where EMPLOYEE_ID=1
"""
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
结果
三、删除
db = pymysql.connect(host='localhost',user='root',password='123456',db='python')
cursor = db.cursor()
sql ="""
delete from EMPLOYEE where EMPLOYEE_ID=1
"""
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
结果
四、查找
db = pymysql.connect(host='localhost',user='root',password='123456',db='python')
cursor = db.cursor()
sql ='select * from employee'
try:
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
print(row)
fname = row[1]
lname = row[2]
age = row[3]
sex = row[4]
income = row[5]
print(f'我是{fname}{lname},今天{age}岁了,性别是{sex},工资是{income}')
except:
print('查询数据出错')
db.close()
结果