Python连接mysql数据库及简单增删改查操作示例代码
作者:崔昕阳 时间:2022-03-10 18:01:57
1.安装pymysql
进入cmd,输入 pip install pymysql:
2.数据库建表
在数据库中,建立一个简单的表,如图:
3.简单操作
3.1查询操作
#coding=utf-8
#连接数据库测试
import pymysql
#打开数据库
db = pymysql.connect(host="localhost",user="root",password="root",db="test")
#使用cursor()方法获取操作游标
cur = db.cursor()
#查询操作
sql = "select * from books"
try:
# 执行sql语句
cur.execute(sql)
results = cur.fetchall()
#遍历结果
for rows in results:
id = rows[0]
name = rows[1]
price = rows[2]
bookcount = rows[3]
author = rows[4]
print("id: {}, name: {}, price: {}, bookcount: {}, author: {}".format(id,name,price,bookcount,author))
except Exception as e:
raise e
finally:
db.close()
运行结果:
3.2插入操作
#coding=utf-8
#插入操作
import pymysql
db = pymysql.connect(host="localhost",user="root",password="root",db="test")
cur = db.cursor()
sql = """insert into books(id,bookname,price,bookCount,author) values (4,'三体',20,3,'刘慈欣')"""
try:
cur.execute(sql)
#提交
db.commit()
except Exception as e:
#错误回滚
db.rollback()
finally:
db.close()
运行结果:
3.3更新操作
#coding=utf-8
#更新操作
import pymysql
db = pymysql.connect(host="localhost",user="root",password="root",db="test")
# 使用cursor()方法获取游标
cur = db.cursor()
sql_update = "update books set bookname = '%s',author = '%s' where id = %d"
try:
cur.execute(sql_update % ("边城","沈从文",4))
#提交
db.commit()
except Exception as e:
#错误回滚
db.rollback()
finally:
db.close()
运行结果:
3.4删除操作
#coding=utf-8
#删除操作
import pymysql
db = pymysql.connect(host="localhost",user="root",password="root",db="test")
#使用cursor()获取操作游标
cur = db.cursor()
sql_delete = "delete from books where id = %d"
try:
#向sql语句传递参数
cur.execute(sql_delete % (1))
#提交
db.commit()
except Exception as e:
#错误回滚
db.rollback()
finally:
db.close()
运行结果:
来源:https://blog.csdn.net/Cuixinyang19_/article/details/80060294
标签:Python,mysql,增删改查
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python常见字符串处理函数与用法汇总
2023-10-19 08:07:11
Mootools 1.2教程(4)——函数
2008-11-18 15:36:00
asp是什么格式 asp文件用什么打开
2020-06-30 16:04:48
PLSQL导入dmp文件的详细完整步骤
2023-06-26 11:45:32
![](https://img.aspxhome.com/file/2023/6/63716_0s.png)
德国ebay购头记
2009-04-29 11:10:00
![](https://img.aspxhome.com/file/UploadPic/20094/29/01-96s.jpg)
ASP怎么谈到应用到类的?
2008-03-10 11:21:00
python中numpy数组的csv文件写入与读取
2021-11-26 06:18:20
python抓取某汽车网数据解析html存入excel示例
2023-11-02 16:46:35
![](https://img.aspxhome.com/file/2023/3/63263_0s.jpg)
mysql limit查询优化分析
2023-11-16 00:51:04
使用Python的Bottle框架写一个简单的服务接口的示例
2023-09-01 17:29:50
将SQL Server中所有表的列信息显示出来
2009-01-08 16:27:00
利用xslt对xml进行缩进格式化处理
2008-09-04 10:34:00
Python读取YAML文件过程详解
2021-04-21 07:12:25
为什么JavaScript中正则表达式的test方法会出错?
2009-03-17 12:38:00
PHP实现的杨辉三角求解算法分析
2023-11-19 13:52:29
![](https://img.aspxhome.com/file/2023/9/55679_0s.jpg)
W3C Group的JavaScript1.8新特性介绍
2009-07-24 12:31:00
JS 去前后空格大全(IE9亲测)
2013-08-22 13:01:43
如何将多宿主计算机配置为允许SQL Server访问
2011-01-04 14:04:00
浅说相册图片详情页面中大图的浏览方式
2009-02-01 18:34:00
![](https://img.aspxhome.com/file/UploadPic/20092/1/12-79.jpg)
php面象对象数据库操作类实例
2023-10-13 22:33:05