Python 操作MySQL详解及实例
使用Python进行MySQL的库主要有三个,Python-MySQL(更熟悉的名字可能是MySQLdb),PyMySQL和SQLAlchemy。
Python-MySQL资格最老,核心由C语言打造,接口精炼,性能最棒,缺点是环境依赖较多,安装复杂,近两年已停止更新,只支持Python2,不支持Python3。
PyMySQL为替代Python-MySQL而生,纯python打造,接口与Python-MySQL兼容,安装方便,支持Python3。
SQLAlchemy是一个ORM框架,它并不提供底层的数据库操作,而是要借助于MySQLdb、PyMySQL等第三方库来完成,目前SQLAlchemy在Web编程领域应用广泛。
本文主要介绍PyMySQL的正确使用方法,示例代码都是选自实战项目。
安装
简单的方式:
pip install pymysql
如果无法联网,需要进行离线安装,例如:
pip install pymysql-x.x.x.tar.gz
导入
import pymysql
连接
def connect_wxremit_db():
return pymysql.connect(host='10.123.5.28',
port=3306,
user='root',
password='root1234',
database='db_name',
charset='latin1')
查询
def query_country_name(cc2):
sql_str = ("SELECT Fcountry_name_zh"
+ " FROM t_country_code"
+ " WHERE Fcountry_2code='%s'" % (cc2))
logging.info(sql_str)
con = mysql_api.connect_wxremit_db()
cur = con.cursor()
cur.execute(sql_str)
rows = cur.fetchall()
cur.close()
con.close()
assert len(rows) == 1, 'Fatal error: country_code does not exists!'
return rows[0][0]
简单插入
def insert_file_rec(self, file_name, file_md5):
con = mysql_api.connect_wxremit_db()
cur = con.cursor()
try:
sql_str = ("INSERT INTO t_forward_file (Ffile_name, Ffile_md5)",
+ " VALUES ('%s', '%s')" % (file_name, file_md5))
cur.execute(sql_str)
con.commit()
except:
con.rollback()
logging.exception('Insert operation error')
raise
finally:
cur.close()
con.close()
批量插入
remit_ids = [('1234', 'CAD'), ('5678', 'HKD')]
con = mysql_api.connect_wxremit_db()
cur = con.cursor()
try:
cur.executemany("INSERT INTO t_order (Fremit_id, Fcur_type, Fcreate_time"
+ " VALUES (%s, %s, now())", new_items)
assert cur.rowcount == len(remit_ids), 'my error message'
con.commit()
except Exception as e:
con.rollback()
logging.exception('Insert operation error')
finally:
cur.close()
con.close()
更新
def update_refund_trans(self, remit_id):
con = mysql_api.connect_wxremit_db()
cur = con.cursor()
try:
sql_str = ("SELECT Fremit_id"
+ " FROM t_wxrefund_trans"
+ " WHERE Fremit_id='%s'" % remit_id
+ " FOR UPDATE")
logging.info(sql_str)
cur.execute(sql_str)
assert cur.rowcount == 1, 'Fatal error: The wx-refund record be deleted!'
sql_str = ("UPDATE t_wxrefund_trans"
+ " SET Fcheck_amount_flag=1"
+ ", Fmodify_time=now()"
+ " WHERE Fremit_id='%s'" % remit_id
logging.info(sql_str)
cur.execute(sql_str)
assert cur.rowcount == 1, 'The number of affected rows not equal to 1'
con.commit()
except:
con.rollback()
logging.exception('Update operation error')
raise
finally:
cur.close()
con.close()
PyMySQL已经相当成熟,和Python-MySQL一样,它在很多Linux发行版本中都是可选的安装组件。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
暂无“Python 操作MySQL详解及实例”评论...
P70系列延期,华为新旗舰将在下月发布
3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。
而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?
根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。
更新动态
2025年11月06日
2025年11月06日
- 小骆驼-《草原狼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]