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多线程ctrl+c退出问题解决方案
Oct 23 Python
Python中数字以及算数运算符的相关使用
Oct 12 Python
使用Python实现一个栈判断括号是否平衡
Aug 23 Python
Pycharm代码无法复制,无法选中删除,无法编辑的解决方法
Oct 22 Python
使用pyshp包进行shapefile文件修改的例子
Dec 06 Python
Django 项目通过加载不同env文件来区分不同环境
Feb 17 Python
python 解压、复制、删除 文件的实例代码
Feb 26 Python
详解Python 中的容器 collections
Aug 17 Python
Python实现七个基本算法的实例代码
Oct 08 Python
Python 实现键盘鼠标按键模拟
Nov 18 Python
conda安装tensorflow和conda常用命令小结
Feb 20 Python
Matplotlib绘制混淆矩阵的实现
May 27 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批量删除数据
2007/01/18 PHP
PHP PDO数据库操作预处理与注意事项
2019/03/16 PHP
PHP7导出Excel报ERR_EMPTY_RESPONSE解决方法
2019/04/16 PHP
javascript中对对层的控制
2006/12/29 Javascript
jQuery 追加元素的方法如append、prepend、before
2014/01/16 Javascript
Javascript window对象详解
2014/11/12 Javascript
jQuery的几个我们必须了解的特点
2015/05/03 Javascript
js获取页面description的方法
2015/05/21 Javascript
jQuery表格插件datatables用法汇总
2016/03/29 Javascript
vue.js选中动态绑定的radio的指定项
2017/06/02 Javascript
解决vue 按钮多次点击重复提交数据问题
2018/05/10 Javascript
Javascript获取某个月的天数
2018/05/30 Javascript
express.js中间件说明详解
2019/03/19 Javascript
vue 集成jTopo 处理方法
2019/08/07 Javascript
Vue实现商品详情页的评价列表功能
2019/09/04 Javascript
js实现移动端吸顶效果
2020/01/08 Javascript
[03:07]【DOTA2亚洲邀请赛】我们,梦开始的地方
2017/03/07 DOTA
在Python中使用lambda高效操作列表的教程
2015/04/24 Python
深入解析Python中的descriptor描述器的作用及用法
2016/06/27 Python
python类的继承实例详解
2017/03/30 Python
简单实现python画圆功能
2018/01/25 Python
基于Python实现的微信好友数据分析
2018/02/26 Python
Python基于递归算法求最小公倍数和最大公约数示例
2018/07/27 Python
Python开发网站目录扫描器的实现
2019/02/21 Python
用Python实现BP神经网络(附代码)
2019/07/10 Python
基于Django统计博客文章阅读量
2019/10/29 Python
python实现扫雷小游戏
2020/04/24 Python
django 数据库 get_or_create函数返回值是tuple的问题
2020/05/15 Python
Ubuntu 20.04安装Pycharm2020.2及锁定到任务栏的问题(小白级操作)
2020/10/29 Python
2014中考励志标语
2014/06/05 职场文书
教师党员学习群众路线心得体会
2014/11/04 职场文书
2014年社区工作总结
2014/11/18 职场文书
2015年大学迎新工作总结
2015/07/16 职场文书
Python图像处理之图像拼接
2021/04/28 Python
mysql insert 存在即不插入语法说明
2022/03/25 MySQL
Linux下使用C语言代码搭建一个简单的HTTP服务器
2022/04/13 Servers