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 02 Python
利用Python爬取可用的代理IP
Aug 18 Python
深入理解NumPy简明教程---数组2
Dec 17 Python
python+opencv实现的简单人脸识别代码示例
Nov 14 Python
Python2包含中文报错的解决方法
Jul 09 Python
python 同时运行多个程序的实例
Jan 07 Python
浅析Python 读取图像文件的性能对比
Mar 07 Python
Python 窗体(tkinter)按钮 位置实例
Jun 13 Python
十行代码使用Python写一个USB病毒
Jun 21 Python
关于阿里云oss获取sts凭证 app直传 python的实例
Aug 20 Python
python 实现turtle画图并导出图片格式的文件
Dec 07 Python
Python 内置函数globals()和locals()对比详解
Dec 23 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
第1次亲密接触PHP5(1)
2006/10/09 PHP
解决phpmyadmin中文乱码问题。。。
2007/01/18 PHP
PHPMYADMIN 简明安装教程 推荐
2010/03/07 PHP
PHP return语句另类用法不止是在函数中
2014/09/17 PHP
修改WordPress中文章编辑器的样式的方法详解
2015/12/15 PHP
PHP加密3DES报错 Call to undefined function: mcrypt_module_open() 如何解决
2016/04/17 PHP
php类的自动加载操作实例详解
2016/09/28 PHP
统计PHP目录中的文件数方法
2019/03/05 PHP
php 命名空间(namespace)原理与用法实例小结
2019/11/13 PHP
WordPress伪静态规则设置代码实例
2020/12/10 PHP
JQuery 将元素显示在屏幕的中央的代码
2010/02/27 Javascript
jQuery实现点击标题输入详细信息
2013/04/16 Javascript
使用JS CSS去除IE链接虚线框的三种方法
2013/11/14 Javascript
For循环中分号隔开的3部分的执行顺序探讨
2014/05/27 Javascript
JS公共小方法之判断对象是否为domElement的实例
2016/11/25 Javascript
Vue-resource实现ajax请求和跨域请求示例
2017/02/23 Javascript
Angular2平滑升级到Angular4的步骤详解
2017/03/29 Javascript
浅谈微信JS-SDK 微信分享接口开发(介绍版)
2018/08/15 Javascript
详解node字体压缩插件font-spider的用法
2018/09/28 Javascript
Django的URLconf中使用缺省视图参数的方法
2015/07/18 Python
python语言中with as的用法使用详解
2018/02/23 Python
PyQt5每天必学之关闭窗口
2018/04/19 Python
python中join()方法介绍
2018/10/11 Python
tensorflow 变长序列存储实例
2020/01/20 Python
TensorFlow的reshape操作 tf.reshape的实现
2020/04/19 Python
Python configparser模块操作代码实例
2020/06/08 Python
python有几个版本
2020/06/17 Python
html5 localStorage本地存储_动力节点Java学院整理
2017/07/06 HTML / CSS
编写一个 C 函数,该函数在一个字符串中找到可能的最长的子字符串,且该字符串是由同一字符组成的
2015/07/23 面试题
CAD制图设计师自荐信
2014/01/29 职场文书
群众路线剖析材料
2014/09/30 职场文书
小学秋季运动会报道稿
2014/09/30 职场文书
作风建设整改方案
2014/10/27 职场文书
2015年教师节新闻稿
2015/07/17 职场文书
2016教师给学生的毕业寄语
2015/12/04 职场文书
vue项目支付功能代码详解
2022/02/18 Vue.js