用pymysql进行数据库的增删改查

1.导入模块,连接数据库,初始化指针
import pymysql
conn = pymysql.connect(“127.0.0.1”,“root”,“123123”,“new_database”,charset=“utf8”)
cursor = conn.cursor()
2.1 增加
#格式:“INSERT INTO 表名(字段1 ,字段2,字段3)VALUES(内容1 ,内容2,内容3);”
sql = “insert into class_mate(date,company,province,price,weight) values (‘1997-1-16’,‘华为’,‘浙江’,‘1999’,‘44’);”
cursor.execute(sql)

2.2 改
#格式:“update 表名 set 字段1=内容1 ,字段2=内容2 where 条件”
sql = “UPDATE class_mate SET date=‘2023-09-21’ where DATE = ‘2018-9-21’;”
cursor.execute(sql)

2.3 查询
#格式:“select 字段 from 表名 where 条件”
sql = “select company,sum(weight) from class_mate where date = ‘2008-7-29’ group by company;”
cursor.execute(sql)
#查看结果
result = cursor.fetchall()
print(result)
2.4删除 慎用!
#格式 “delete from 表名 where 条件;”
sql = “delete from class_mate where date = ‘2008-7-21’;”
cursor.execute(sql)
3.关闭连接,增加修改删除均需要提交
conn.commit()
conn.close()

发布了8 篇原创文章 · 获赞 0 · 访问量 49

猜你喜欢

转载自blog.csdn.net/I__INIT/article/details/105089174