python操作MySQL数据库的方法分享


Posted in Python onMay 29, 2012

我采用的是MySQLdb操作的MYSQL数据库。先来一个简单的例子吧:

import MySQLdb try: 
conn=MySQLdb.connect(host='localhost',user='root',passwd='root',db='test',port=3306) 
cur=conn.cursor() 
cur.execute('select * from user') 
cur.close() 
conn.close() 
except MySQLdb.Error,e: 
print "Mysql Error %d: %s" % (e.args[0], e.args[1])

请注意修改你的数据库,主机名,用户名,密码。

下面来大致演示一下插入数据,批量插入数据,更新数据的例子吧:

import MySQLdb try: 
conn=MySQLdb.connect(host='localhost',user='root',passwd='root',port=3306) 
cur=conn.cursor() 
cur.execute('create database if not exists python') 
conn.select_db('python') 
cur.execute('create table test(id int,info varchar(20))') 
value=[1,'hi rollen'] 
cur.execute('insert into test values(%s,%s)',value) 
values=[] 
for i in range(20): 
values.append((i,'hi rollen'+str(i))) 
cur.executemany('insert into test values(%s,%s)',values) 
cur.execute('update test set info="I am rollen" where id=3') 
conn.commit() 
cur.close() 
conn.close() 
except MySQLdb.Error,e: 
print "Mysql Error %d: %s" % (e.args[0], e.args[1])

请注意一定要有conn.commit()这句来提交事务,要不然不能真正的插入数据。

运行之后我的MySQL数据库的结果就不上图了。

import MySQLdb try: 
conn=MySQLdb.connect(host='localhost',user='root',passwd='root',port=3306) 
cur=conn.cursor() 
conn.select_db('python') 
count=cur.execute('select * from test') 
print 'there has %s rows record' % count 
result=cur.fetchone() 
print result 
print 'ID: %s info %s' % result 
results=cur.fetchmany(5) 
for r in results: 
print r 
print '=='*10 
cur.scroll(0,mode='absolute') 
results=cur.fetchall() 
for r in results: 
print r[1] 

conn.commit() 
cur.close() 
conn.close() 
except MySQLdb.Error,e: 
print "Mysql Error %d: %s" % (e.args[0], e.args[1])

运行结果就不贴了,太长了。

查询后中文会正确显示,但在数据库中却是乱码的。经过我从网上查找,发现用一个属性有可搞定:

在Python代码

conn = MySQLdb.Connect(host='localhost', user='root', passwd='root', db='python') 中加一个属性:
改为:
conn = MySQLdb.Connect(host='localhost', user='root', passwd='root', db='python',charset='utf8')
charset是要跟你数据库的编码一样,如果是数据库是gb2312 ,则写charset='gb2312'。

下面贴一下常用的函数:

然后,这个连接对象也提供了对事务操作的支持,标准的方法
commit() 提交
rollback() 回滚

cursor用来执行命令的方法:
callproc(self, procname, args):用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数
execute(self, query, args):执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数
executemany(self, query, args):执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
nextset(self):移动到下一个结果集

cursor用来接收返回值的方法:
fetchall(self):接收全部的返回结果行.
fetchmany(self, size=None):接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.
fetchone(self):返回一条结果行.
scroll(self, value, mode='relative'):移动指针到某一行.如果mode='relative',则表示从当前所在行移动value条,如果 mode='absolute',则表示从结果集的第一行移动value条.

参考资料:

MySQLdb‘s user guide

package MySQLdb

Python 相关文章推荐
python 类详解及简单实例
Mar 24 Python
python常见排序算法基础教程
Apr 13 Python
Python中turtle作图示例
Nov 15 Python
对Python捕获控制台输出流的方法详解
Jan 07 Python
python爬取Ajax动态加载网页过程解析
Sep 05 Python
浅谈Django+Gunicorn+Nginx部署之路
Sep 11 Python
Pytorch之卷积层的使用详解
Dec 31 Python
Python如何在windows环境安装pip及rarfile
Jun 15 Python
卸载tensorflow-cpu重装tensorflow-gpu操作
Jun 23 Python
Pytest单元测试框架如何实现参数化
Sep 05 Python
如何在Python3中使用telnetlib模块连接网络设备
Sep 21 Python
详解Python中的for循环
Apr 30 Python
python利用elaphe制作二维条形码实现代码
May 25 #Python
用python实现批量重命名文件的代码
May 25 #Python
删除目录下相同文件的python代码(逐级优化)
May 25 #Python
ssh批量登录并执行命令的python实现代码
May 25 #Python
巧用Python装饰器 免去调用父类构造函数的麻烦
May 18 #Python
Python使用Socket(Https)Post登录百度的实现代码
May 18 #Python
写了个监控nginx进程的Python脚本
May 10 #Python
You might like
PHP聊天室技术
2006/10/09 PHP
获取php页面执行时间,数据库读写次数,函数调用次数等(THINKphp)
2013/06/03 PHP
php源码分析之DZX1.5字符串截断函数cutstr用法
2015/06/17 PHP
基于JQuery+PHP编写砸金蛋中奖程序
2015/09/08 PHP
PHP连接MYSQL数据库的3种常用方法
2017/02/27 PHP
thinkPHP5框架接口写法简单示例
2019/08/05 PHP
laravel dingo API返回自定义错误信息的实例
2019/09/29 PHP
tp5框架基于ajax实现异步删除图片的方法示例
2020/02/10 PHP
解析JavaScript中delete操作符不能删除的对象
2013/12/03 Javascript
jquery性能优化高级技巧
2015/08/24 Javascript
jQuery带时间的日期控件代码分享
2015/08/26 Javascript
JavaScript制作淘宝星级评分效果的思路
2020/06/23 Javascript
JavaScript学习小结(7)之JS RegExp
2015/11/29 Javascript
理解javascript中的MVC模式
2016/01/28 Javascript
微信小程序上滑加载下拉刷新(onscrollLower)分批加载数据(二)
2017/05/11 Javascript
JS+WCF实现进度条实时监测数据加载量的方法详解
2017/12/19 Javascript
Layui Form 自定义验证的实例代码
2019/09/14 Javascript
Antd下拉选择,自动匹配功能的实现
2020/10/24 Javascript
使用jQuery实现购物车
2020/10/29 jQuery
[01:00:14]2018DOTA2亚洲邀请赛 4.6 淘汰赛 VP vs TNC 第三场
2018/04/10 DOTA
Python中的Numpy入门教程
2014/04/26 Python
跟老齐学Python之网站的结构
2014/10/24 Python
Python数据结构与算法之使用队列解决小猫钓鱼问题
2017/12/14 Python
python画图把时间作为横坐标的方法
2019/07/07 Python
python爬虫的一个常见简单js反爬详解
2019/07/09 Python
django 数据库连接模块解析及简单长连接改造方法
2019/08/29 Python
Win10里python3创建虚拟环境的步骤
2020/01/31 Python
3种适用于Python的疯狂秘密武器及原因解析
2020/04/29 Python
Django权限设置及验证方式
2020/05/13 Python
PyCharm2020.3.2安装超详细教程
2021/02/08 Python
FC-Moto美国:欧洲最大的摩托车服装和头盔商店之一
2019/08/24 全球购物
DOM和JQuery对象有什么区别
2016/11/11 面试题
教师实习期自我鉴定
2013/10/06 职场文书
小学生期末自我鉴定
2014/01/19 职场文书
遥感技术与仪器求职信
2014/02/22 职场文书
党的群众路线教育实践活动调研报告
2014/11/03 职场文书