import pymysql
db = pymysql.connect(host='localhost', user='root', password='admin', db='world')
# 获取游标
cur = db.cursor()
#查
def select():
sql_select='SELECT * FROM test_table'
# 执行
cur.execute(sql_select)
# 通过fetchall方法获取数据
result=cur.fetchall()
print(format(result))
#插
def insert():
sql_Insert="""insert into world.test_table(phone,dt,id) values ('666','20211210','1002')"""
try:
cur.execute(sql_Insert)
db.commit()
except Exception as e:
db.rollback()
#更新
def update():
update_sql="update world.test_table set phone='777',dt='20211210' where id='1002'"
try:
cur.execute(update_sql)
db.commit()
except Exception as e:
db.rollback()
#删除
def delete():
delete_sql="delete from world.test_table where id='1002' limit 1"
try:
cur.execute(delete_sql)
db.commit()
except Exception as e:
db.rollback()
db.close()
if __name__ == '__main__':
insert()
update()
delete()
select()
Python连接mysql数据库及简单增删改查操作
最新推荐文章于 2024-04-06 19:37:00 发布