python操作MySQL数据库具体方法


Posted in Python onOctober 28, 2013
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 MySQLdbtry:
    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 MySQLdbtry:
    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条.

Python 相关文章推荐
Python实现的简单发送邮件脚本分享
Nov 07 Python
python类装饰器用法实例
Jun 04 Python
浅谈python新手中常见的疑惑及解答
Jun 14 Python
python3大文件解压和基本操作
Dec 15 Python
Java与Python两大幸存者谁更胜一筹呢
Apr 12 Python
解决phantomjs截图失败,phantom.exit位置的问题
May 17 Python
利用python Selenium实现自动登陆京东签到领金币功能
Oct 31 Python
Python爬虫实现百度翻译功能过程详解
May 29 Python
python re.match()用法相关示例
Jan 27 Python
Python趣味爬虫之用Python实现智慧校园一键评教
May 28 Python
Python 如何利用ffmpeg 处理视频素材
Nov 27 Python
python实现会员信息管理系统(List)
Mar 18 Python
Python sys.path详细介绍
Oct 17 #Python
python开发的小球完全弹性碰撞游戏代码
Oct 15 #Python
python中 ? : 三元表达式的使用介绍
Oct 09 #Python
Python 文件和输入输出小结
Oct 09 #Python
Python 错误和异常小结
Oct 09 #Python
Python 命令行非阻塞输入的小例子
Sep 27 #Python
用Python脚本生成Android SALT扰码的方法
Sep 18 #Python
You might like
php计算函数执行时间的方法
2015/03/20 PHP
php实现给二维数组中所有一维数组添加值的方法
2017/02/04 PHP
php正则表达式使用方法整理集合
2020/01/31 PHP
JQuery UI皮肤定制
2009/07/27 Javascript
js将控件隐藏的方法及display属性介绍
2013/07/04 Javascript
通过JS来判断页面控件是否获取焦点
2014/01/03 Javascript
ie浏览器使用js导出网页到excel并打印
2014/03/11 Javascript
JQuery实现Ajax加载图片的方法
2015/12/24 Javascript
基于Turn.js 实现翻书效果实例解析
2016/06/20 Javascript
AngularJs ng-route路由详解及实例代码
2016/09/14 Javascript
深入理解JavaScript定时机制
2016/10/27 Javascript
js以分隔符分隔数组中的元素并转换为字符串的方法
2016/11/16 Javascript
浅谈AngularJs 双向绑定原理(数据绑定机制)
2017/12/07 Javascript
详解js创建对象的几种方法及继承
2019/04/12 Javascript
TypeScript开发Node.js程序的方法
2019/04/30 Javascript
[01:07:53]RNG vs VG 2019国际邀请赛小组赛 BO2 第一场 8.15
2019/08/17 DOTA
归纳整理Python中的控制流语句的知识点
2015/04/14 Python
今天 平安夜 Python 送你一顶圣诞帽 @微信官方
2017/12/25 Python
快速解决PyCharm无法引用matplotlib的问题
2018/05/24 Python
如何在django里上传csv文件并进行入库处理的方法
2019/01/02 Python
python远程邮件控制电脑升级版
2019/05/23 Python
python判断所输入的任意一个正整数是否为素数的两种方法
2019/06/27 Python
Python短信轰炸的代码
2020/03/25 Python
详解tensorflow之过拟合问题实战
2020/11/01 Python
python中PyQuery库用法分享
2021/01/15 Python
突袭HTML5之Javascript API扩展5—其他扩展(应用缓存/服务端消息/桌面通知)
2013/01/31 HTML / CSS
Strathberry苏贝瑞中国官网:西班牙高级工匠手工打造
2020/10/19 全球购物
澳大利亚厨房和家用电器购物网站:Bing Lee
2021/01/11 全球购物
小学生国旗下演讲稿
2014/04/25 职场文书
会计专业毕业生求职信
2014/07/04 职场文书
承诺书样本
2014/08/30 职场文书
高考诚信考试承诺书
2015/04/29 职场文书
团拜会主持词
2015/07/04 职场文书
详细介绍python类及类的用法
2021/05/31 Python
css实现两栏布局,左侧固定宽,右侧自适应的多种方法
2021/08/07 HTML / CSS
Java 异步任务计算FutureTask
2022/04/28 Java/Android