本文实例讲述了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方法用来和数据库建立连接,接收数个参数,返回连接对象:

代码如下:
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() 回滚

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

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

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

二、cursor方法执行与返回值

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

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

三、数据库操作

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

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

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

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

3、其他实例及参数配置

文件路径MysqlDb->baseinfo->__init__

#-*-coding:utf-8-*-
# Time:2017/9/19 18:26
# Author:YangYangJun myhost="localhost"
myuser="myself"
mypasswd="skyyj"
mydb="mystudy"
myport=53306
#charSet="utf8"

文件路径MysqlDb->myselfDb

#-*-coding:utf-8-*-
# Time:2017/9/19 19:52
# Author:YangYangJun import MySQLdb
import time import baseinfo host = baseinfo.myhost
user = baseinfo.myuser
passwd = baseinfo.mypasswd
db = baseinfo.mydb
port = baseinfo.myport #建立连接 myConnect = MySQLdb.connect(host,user,passwd,db,port,charset= 'utf8') #打开游标 myCursor = myConnect.cursor() myselect = "select * from luckynumber where LID >= '%d'" %(24) myCursor.execute(myselect) result = myCursor.fetchone()
print result #执行插入
create_time = time.strftime('%Y-%m-%d %H:%M:%S')
update_time = time.strftime('%Y-%m-%d %H:%M:%S')
name = '杨要军'
Remark = '测试数据' myinsert= "insert into mytest(username,name,CreateTime,ModifyTime,Remark) " \
"VALUES ('%s','%s','%s','%s','%s')" \
%('Yang',name,create_time,update_time,Remark) try:
print "执行插入"
exeinsert = myCursor.execute(myinsert)
print exeinsert
myConnect.commit()
except UnicodeEncodeError as e:
#发生错误时回滚
print '执行回滚'
print e
myConnect.rollback() mytestsele = "select name from mytest where id = '%d'" %(9) myCursor.execute(mytestsele) seleresult = myCursor.fetchone()
print seleresult
print "seleresult :%s" % seleresult #执行更新 myupdate = "update mytest set name = '%s' where id > '%d' " %("李雷",9) try:
print "执行更新"
myCursor.execute(myupdate)
myConnect.commit()
except UnicodeEncodeError as e:
print "执行回滚"
print e
myCursor.rollback() mytestsele = "select name from mytest where id = '%d'" %(10) myCursor.execute(mytestsele) seleresult = myCursor.fetchone()
print seleresult
print "seleresult :%s" % seleresult #执行删除 mydelet = "delete from mytest where id < '%d'" % (9) try:
print "执行删除"
myCursor.execute(mydelet)
myConnect.commit()
except UnicodeEncodeError as e:
print "执行回滚"
print e
myCursor.rollback() mytestsele = "select name from mytest where id = '%d'" %(10) myCursor.execute(mytestsele) seleresult = myCursor.fetchone()
print seleresult
print "seleresult :%s" % seleresult myConnect.close

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

#打开数据库连接
#此处要加上端口,port且值是整型,不必加引号,如果加引号,会报错:TypeError: an integer is required。如果数据库端口为:3306.则可不填写端口,非默认端口,必须填写端口信息
#写法一:
#DbConnect = MySQLdb.connect(host="dbhost",user="dbuser",passwd="dbpassword",db="database",port=13306,charset="utf8") #写法二: #DbConnect = MySQLdb.connect('dbhost','dbuser','dbpassword','database',13306,'utf8') #写法三: 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. 【题解】Luogu CF343D Water Tree

    原题传送门:CF343D Water Tree 这道题要用树链剖分,我博客里有对树链剖分的详细介绍 这明显是弱智题 树剖套珂朵莉树多简单啊 前置芝士:珂朵莉树 窝博客里对珂朵莉树的介绍 没什么好说的自 ...

  2. python简说(二十三)发邮件

    import yagmailusername='uitestp4p@163.com'password='houyafan123'#生成授权码,qq.163.126都是授权码 mail_server = ...

  3. JQuery 实现 倒计时 按钮具体方法

    <head> <title>test count down button</title> <script src="http://ajax.aspn ...

  4. 【转】RHEL(RedHat Enterprise Linux)5/6 ISO镜像下载

    本文贴出了RHEL(RedHat Enterprise Linux)发行版本中常用的服务器版本的ISO镜像文件,供大家下载学习使用,贴出的版本有RedHat Enterprise Linux(RHEL ...

  5. 2018年11月16日 我和SB交流有代沟-继续字符串4

    test="abcdeffedcba" v=test.lstrip("bcabc")#寻找的是最多匹配然后移除指定字符串 print("1.lstri ...

  6. Linux使用——Linux命令——Linux文件压缩和解压使用记录

    一:tar(可压缩可解压) tar命令是Unix/Linux系统中备份文件的可靠方法,几乎可以工作于任何环境中,它的使用权限是所有用户.但是tar本身只是一个文件打包工具,只有和其他工具组合时才具有压 ...

  7. Python3 tkinter基础 Entry validate validatecommand 失去焦点时,检查输入内容

             Python : 3.7.0          OS : Ubuntu 18.04.1 LTS         IDE : PyCharm 2018.2.4       Conda ...

  8. Git学习笔记---协作的一般流程

    一般的操作流程 1.pull 王小坤与另一个同事张大炮一起开发一个项目,张大炮昨天修改了数据库读写的api,优化了执行速度,并把read()函数改名成了Read(),下午下班之前把这些代码push到服 ...

  9. hihoCoder week12 刷油漆

    题目链接: https://hihocoder.com/contest/hiho12/problem/1 给出一棵树 每个节点的价值 求以1为根的树中,选取m个相联通的节点的最大价值和 #includ ...

  10. Install and Compile MatConvNet: CNNs for MATLAB --- Deep Learning framework

    Install and Compile MatConvNet: CNNs for MATLAB --- Deep Learning framework 2017-04-18  10:19:35 If ...