折腾好半天的数据库连接,由于之前未安装 pip ,而且自己用的python 版本为3.6. 只能用 pymysql 来连接数据库,下边 简单介绍一下 连接的过程,以及简单的增删改查操作。
1.通过 pip 安装 pymysql
进入 cmd"//img.jbzj.com/file_images/article/202002/2020210161514990.png" alt="" />
安装完成后出现如图相关信息,表示安装成功。
2.测试连接
import pymysql #导入 pymysql
如果编译未出错,即表示 pymysql 安装成功
简单的增删改查操作
示例表结构
2.1查询操作i
import pymysql #导入 pymysql
#打开数据库连接
db= pymysql.connect(host="localhost",user="root",
password="123456",db="test",port=3307)
# 使用cursor()方法获取操作游标
cur = db.cursor()
#1.查询操作
# 编写sql 查询语句 user 对应我的表名
sql = "select * from user"
try:
cur.execute(sql) #执行sql语句
results = cur.fetchall() #获取查询的所有记录
print("id","name","password")
#遍历结果
for row in results :
id = row[0]
name = row[1]
password = row[2]
print(id,name,password)
except Exception as e:
raise e
finally:
2.2插入操作
import pymysql #2.插入操作 db= pymysql.connect(host="localhost",user="root", password="123456",db="test",port=3307) # 使用cursor()方法获取操作游标 cur = db.cursor() sql_insert ="""insert into user(id,username,password) values(4,'liu','1234')""" try: cur.execute(sql_insert) #提交 db.commit() except Exception as e: #错误回滚 db.rollback() finally: db.close()
2.3更新操作
import pymysql
#3.更新操作
db= pymysql.connect(host="localhost",user="root",
password="123456",db="test",port=3307)
# 使用cursor()方法获取操作游标
cur = db.cursor()
sql_update ="update user set username = '%s' where id = %d"
try:
cur.execute(sql_update % ("xiongda",3)) #像sql语句传递参数
#提交
db.commit()
except Exception as e:
#错误回滚
db.rollback()
finally:
db.close()
2.4删除操作
import pymysql #4.删除操作 db= pymysql.connect(host="localhost",user="root", password="123456",db="test",port=3307) # 使用cursor()方法获取操作游标 cur = db.cursor() sql_delete ="delete from user where id = %d" try: cur.execute(sql_delete % (3)) #像sql语句传递参数 #提交 db.commit() except Exception as e: #错误回滚 db.rollback() finally: db.close()
更多关于python3.6 连接mysql数据库及增删改查操作的相关文章大家可以点击下面的相关链接
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
暂无“python3.6连接mysql数据库及增删改查操作详解”评论...
更新动态
2025年10月29日
2025年10月29日
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]
