本文实例讲述了python中MySQLdb模块用法。分享给大家供大家参考。具体用法分析如下:

MySQLdb其实有点像php或asp中连接数据库的一个模式了,只是MySQLdb是针对mysql连接了接口,我们可以在python中连接MySQLdb来实现数据的各种操作。

python连接mysql的方案有oursql、PyMySQL、 myconnpy、MySQL Connector 等,不过本篇要说的确是另外一个类库MySQLdb,MySQLdb 是用于Python链接Mysql数据库的接口,它实现了 Python 数据库 API 规范 V2.0,基于 MySQL C API 上建立的。可以从:https://pypi.python.org/pypi/MySQL-python 进行获取和安装,而且很多发行版的linux源里都有该模块,可以直接通过源安装。

一、数据库连接

MySQLdb提供了connect方法用来和数据库建立连接,接收数个参数,返回连接对象:

代码如下:
  1. DbConnect = MySQLdb.connect(host="dbhost",user="username",passwd="password",db="databasename",port=13306,charset="utf8")

比较常用的参数包括:

host:数据库主机名.默认是用本地主机
user:数据库登陆名.默认是当前用户
passwd:数据库登陆的秘密.默认为空
db:要使用的数据库名.没有默认值
port:MySQL服务使用的TCP端口.默认是3306,如果端口是3306可以不写端口,反之必须填写端口。
charset:数据库编码
更多关于参数的信息可以查这里 http://mysql-python.sourceforge.net/MySQLdb.html

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

看一个简单的查询示例如下:

  1. # encoding: utf-8
  2. import MySQLdb
  3. # 打开数据库连接
  4. db =MySQLdb.connect(host,user,passwd,db,port,charset= 'utf8')
  1. # 使用cursor()方法获取操作游标
    cursor = db.cursor()
  2.  
  3. # 使用execute方法执行SQL语句
    cursor.execute("SELECT VERSION()")
  4.  
  5. # 使用 fetchone() 方法获取一条数据库。
    data = cursor.fetchone()
  6.  
  7. print "Database version : %s " % data
  8.  
  9. # 关闭数据库连接
    db.close()

脚本执行结果如下:
Database version : 5.6.30-log

二、cursor方法执行与返回值

cursor方法提供两类操作:1.执行命令,2.接收返回值 。
cursor用来执行命令的方法

  1. #用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数
  2. callproc(self, procname, args)
  3. #执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数
  4. execute(self, query, args)
  5. #执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
  6. executemany(self, query, args)
  7. #移动到下一个结果集
  8. nextset(self)
  9. cursor用来接收返回值的方法
  10. #接收全部的返回结果行.
  11. fetchall(self)
  12. #接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据
  13. fetchmany(self, size=None)
  14. #返回一条结果行
  15. fetchone(self)
  16. #移动指针到某一行.如果mode='relative',则表示从当前所在行移动value条,如果mode='absolute',则表示从结果集的第一行移动value条
  17. scroll(self, value, mode='relative')
  18. #这是一个只读属性,并返回执行execute()方法后影响的行数
  19. rowcount

三、数据库操作

1、创建database tables
如果数据库连接存在我们可以使用execute()方法来为数据库创建表,如下所示创建表mytest:

  1. # encoding: utf-8
  2. import MySQLdb
  3. # 打开数据库连接
  4. db = MySQLdb.connect(host,user,passwd,db,port,charset= 'utf8')
  5. # 使用cursor()方法获取操作游标
  6. cursor = db.cursor()
  7. # 如果数据表已经存在使用 execute() 方法删除表。
  8. cursor.execute("DROP TABLE IF EXISTS mytest")
  9. # 创建数据表SQL语句
  10. sql = """CREATE TABLE `mytest` (
  11. `id` int(10) NOT NULL AUTO_INCREMENT COMMENT '主键id',
  12. `username` varchar(50) NOT NULL COMMENT '用户名',
  13. `name` varchar(50) NOT NULL COMMENT '姓名',
  14. `CreateTime` datetime DEFAULT NULL COMMENT '创建时间',
  15. `ModifyTime` datetime DEFAULT NULL COMMENT '修改时间',
  16. `Remark` varchar(100) DEFAULT NULL COMMENT '备注',
  17. PRIMARY KEY (`id`) )"""
  18. cursor.execute(sql)
  19. # 关闭数据库连接
  20. db.close()

2、数据库查询操作
以查询mytest表中id字段大于9的所有数据为例:

  1. # encoding: utf-8
  2. import MySQLdb
  3. # 打开数据库连接
  4. db == MySQLdb.connect(host,user,passwd,db,port,charset= 'utf8')
  5. # 使用cursor()方法获取操作游标
  6. cursor = db.cursor()
  7. # SQL 查询语句
  8. sql = ""select * from mytest where id > '%d'" %(9)
  9. try:
  10. # 执行SQL语句
  11. cursor.execute(sql)
  12. # 获取所有记录列表
  13. results = cursor.fetchall()
  14. for row in results:
  15. id= row[0]
  16. username= row[1]
  17. name= row[2]
  18. CreateTime= row[3]
  19. ModifyTime= row[4]
  20. Remark = row[5]
  21. # 打印结果
  22. print "id=%d,username=%s,name=%d,CreateTime=%s,ModifyTime=%d,Remark = %s" %(id, username, name, CreateTime, ModifyTime,Remark )
  23. except:
  24. print "Error: unable to fecth data"
  25. # 关闭数据库连接
  26. db.close()

3、其他实例及参数配置

文件路径MysqlDb->baseinfo->__init__

  1. #-*-coding:utf-8-*-
  2. # Time:2017/9/19 18:26
  3. # Author:YangYangJun
  4.  
  5. myhost="localhost"
  6. myuser="myself"
  7. mypasswd="skyyj"
  8. mydb="mystudy"
  9. myport=53306
  10. #charSet="utf8"

文件路径MysqlDb->myselfDb

  1. #-*-coding:utf-8-*-
  2. # Time:2017/9/19 19:52
  3. # Author:YangYangJun
  4.  
  5. import MySQLdb
  6. import time
  7.  
  8. import baseinfo
  9.  
  10. host = baseinfo.myhost
  11. user = baseinfo.myuser
  12. passwd = baseinfo.mypasswd
  13. db = baseinfo.mydb
  14. port = baseinfo.myport
  15.  
  16. #建立连接
  17.  
  18. myConnect = MySQLdb.connect(host,user,passwd,db,port,charset= 'utf8')
  19.  
  20. #打开游标
  21.  
  22. myCursor = myConnect.cursor()
  23.  
  24. myselect = "select * from luckynumber where LID >= '%d'" %(24)
  25.  
  26. myCursor.execute(myselect)
  27.  
  28. result = myCursor.fetchone()
  29. print result
  30.  
  31. #执行插入
  32. create_time = time.strftime('%Y-%m-%d %H:%M:%S')
  33. update_time = time.strftime('%Y-%m-%d %H:%M:%S')
  34. name = '杨要军'
  35. Remark = '测试数据'
  36.  
  37. myinsert= "insert into mytest(username,name,CreateTime,ModifyTime,Remark) " \
  38. "VALUES ('%s','%s','%s','%s','%s')" \
  39. %('Yang',name,create_time,update_time,Remark)
  40.  
  41. try:
  42. print "执行插入"
  43. exeinsert = myCursor.execute(myinsert)
  44. print exeinsert
  45. myConnect.commit()
  46. except UnicodeEncodeError as e:
  47. #发生错误时回滚
  48. print '执行回滚'
  49. print e
  50. myConnect.rollback()
  51.  
  52. mytestsele = "select name from mytest where id = '%d'" %(9)
  53.  
  54. myCursor.execute(mytestsele)
  55.  
  56. seleresult = myCursor.fetchone()
  57. print seleresult
  58. print "seleresult :%s" % seleresult
  59.  
  60. #执行更新
  61.  
  62. myupdate = "update mytest set name = '%s' where id > '%d' " %("李雷",9)
  63.  
  64. try:
  65. print "执行更新"
  66. myCursor.execute(myupdate)
  67. myConnect.commit()
  68. except UnicodeEncodeError as e:
  69. print "执行回滚"
  70. print e
  71. myCursor.rollback()
  72.  
  73. mytestsele = "select name from mytest where id = '%d'" %(10)
  74.  
  75. myCursor.execute(mytestsele)
  76.  
  77. seleresult = myCursor.fetchone()
  78. print seleresult
  79. print "seleresult :%s" % seleresult
  80.  
  81. #执行删除
  82.  
  83. mydelet = "delete from mytest where id < '%d'" % (9)
  84.  
  85. try:
  86. print "执行删除"
  87. myCursor.execute(mydelet)
  88. myConnect.commit()
  89. except UnicodeEncodeError as e:
  90. print "执行回滚"
  91. print e
  92. myCursor.rollback()
  93.  
  94. mytestsele = "select name from mytest where id = '%d'" %(10)
  95.  
  96. myCursor.execute(mytestsele)
  97.  
  98. seleresult = myCursor.fetchone()
  99. print seleresult
  100. print "seleresult :%s" % seleresult
  101.  
  102. myConnect.close

注:建立数据库连接的几种写法。对于中文字符,定义连接时,一定要加上charset的参数及值。

  1. #打开数据库连接
  2. #此处要加上端口,port且值是整型,不必加引号,如果加引号,会报错:TypeError: an integer is required。如果数据库端口为:3306.则可不填写端口,非默认端口,必须填写端口信息
  3. #写法一:
  4. #DbConnect = MySQLdb.connect(host="dbhost",user="dbuser",passwd="dbpassword",db="database",port=13306,charset="utf8")
  5.  
  6. #写法二:
  7.  
  8. #DbConnect = MySQLdb.connect('dbhost','dbuser','dbpassword','database',13306,'utf8')
  9.  
  10. #写法三:
  11.  
  12. DbConnect = MySQLdb.connect(host,user,passwd,db,port,charset= 'utf8')

Python2 - MySQL适配器 MySQLdb的更多相关文章

  1. Python3 - MySQL适配器 PyMySQL

    本文我们为大家介绍 Python3 使用 PyMySQL 连接数据库,并实现简单的增删改查. 什么是 PyMySQL? PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一 ...

  2. python2.7中MySQLdb的安装与使用详解

    Python2.7中MySQLdb的使用 import MySQLdb #1.建立连接 connect = MySQLdb.connect( '127.0.0.1', #数据库地址 'root', # ...

  3. Python与数据库[1] -> 数据库接口/DB-API[1] -> MySQL 适配器

    MySQL适配器 / MySQL Adapter MySQL是一种关系型数据库,下面主要介绍利用如何利用Python的MySQL适配器来对MySQL进行操作,其余内容可参考文末相关阅读. 1 MySQ ...

  4. 快速熟悉python 下使用mysql(MySQLdb)

    首先你需要安装上mysql和MySQLdb模块(当然还有其他模块可以用),这里我就略过了,如果遇到问题自行百度(或者评论在下面我可以帮忙看看) 这里简单记录一下自己使用的学习过程: 一.连接数据库 M ...

  5. python2.7之MySQLdb模块 for linux安装

    1.下载:MySQL-pythonhttp://sourceforge.net/projects/mysql-python/files/mysql-python-test/1.2.3b1/MySQL- ...

  6. Ubuntu安装Mysql+Django+MySQLdb

    安装Mysql sudo apt-get install mysql-server mysql-client root@IdeaPad:/# mysql -u root -p Enter passwo ...

  7. 【mysql】MySQLdb中的事务处理

    MySQL数据库有一个自动提交事务的概念,autocommit.含义是,如果开启autocommit, 则每一个语句执行后会自动提交.即一个语句视为一个事务. 在python使用的MySQLdb中,默 ...

  8. windows环境python2.7安装MySQLdb

    我电脑是64位,并且安装python不是默认路径,使用pip和mysql-python的exe文件安装都失败了. 后在网上找到一种安装方法,记录下. 确保安装了wheel,我的2.7默认安装了 pip ...

  9. 【mysql】MySQLdb返回字典方法

    来源:http://blog.csdn.net/zgl_dm/article/details/8710371 默认mysqldb返回的是元组,这样对使用者不太友好,也不利于维护下面是解决方法 impo ...

随机推荐

  1. request 模块详细介绍

    request 模块详细介绍 request Requests 是使用 Apache2 Licensed 许可证的 基于Python开发的HTTP 库,其在Python内置模块的基础上进行了高度的封装 ...

  2. intel webrtc 部署

    org link conference server Configure the MCU server 1. set the maximum numbers of open files, runnin ...

  3. EXP7 网络欺诈技术防范(修改版)

    实践内容 本实践的目标理解常用网络欺诈背后的原理,以提高防范意识,并提出具体防范方法. 1.简单应用SET工具建立冒名网站 2.ettercap DNS spoof 3.结合应用两种技术,用DNS s ...

  4. hdu 1394 Minimum Inversion Number - 树状数组

    The inversion number of a given number sequence a1, a2, ..., an is the number of pairs (ai, aj) that ...

  5. 【Python020--内嵌函数和闭包】

    一.内嵌函数&闭包 1.最好是访问全局变量而不是修改全局变量,修改全局变量Python会内部屏蔽(修改后,函数会内部创建一个和全局变量一抹一样的变量) >>> count = ...

  6. 给sublime设置格式化代码的快捷键

    sublime中自建的有格式化按钮: Edit  ->  Line  ->  Reindent 只是sublime并没有给他赋予快捷键,所以只需加上快捷键即可 Preference  -& ...

  7. Restful framework【第四篇】视图组件

    基本使用 -view的封装过程有空可以看一下 -ViewSetMixin # ViewSetMixin 写在前面,先找ViewSetMixin的as_view方法 # 用了ViewSetMixin , ...

  8. P4137 Rmq Problem / mex

    目录 链接 思路 线段树 莫队 链接 https://www.luogu.org/problemnew/show/P4137 思路 做了好几次,每次都得想一会,再记录一下 可持久化权值线段树 区间出现 ...

  9. 密码发生器|2012年蓝桥杯B组题解析第八题-fishers

    (10')密码发生器 在对银行账户等重要权限设置密码的时候,我们常常遇到这样的烦恼:如果为了好记用生日吧,容易被破解,不安全:如果设置不好记的密码,又担心自己也会忘记:如果写在纸上,担心纸张被别人发现 ...

  10. 奇怪的比赛|2012年蓝桥杯B组题解析第四题-fishers

    (8')奇怪的比赛 某电视台举办了低碳生活大奖赛.题目的计分规则相当奇怪: 每位选手需要回答10个问题(其编号为1到10),越后面越有难度.答对的,当前分数翻倍:答错了则扣掉与题号相同的分数(选手必须 ...