本文实例讲述了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. 【题解】bzoj 4478 [Jsoi2013]侦探jyy

    原题传送门 弱智搜索题 我们就枚举每个点,先判断它是否必须发生,如果没有必须发生,开始搜索它的祖先,如果祖先中有必须发生的,那么它就必须发生,如果祖先中没有必须发生的,那么搜索所有入度为0的点(除了它 ...

  2. 02: docker高级篇

    1.1 Docker Compose 1.Docker Compose 介绍 1. Compose是一个定义和管理多容器的工具,使用Python语言编写. 2. 使用Compose配置文件描述多个容器 ...

  3. 将svn下载的项目转化为java project

    1.选中项目,右键点击弹出窗口,点击窗口中的[Properties],弹出[Properties for test]窗口, 如下: 2.点击窗口中的[Project Facets],右边显示[Conv ...

  4. topcoder srm 380 div1

    problem1 link 分类讨论.高度没有太大关系.主要看长度. problem2 link 二分答案$mid$.计算每种$card$不足的部分,加起来,小于等于$min(jokers,mid)$ ...

  5. Flask学习【第4篇】:用Flask的扩展实现的简单的页面登录

    from flask import Flask,render_template,request,redirect,session app = Flask(__name__,template_folde ...

  6. Visual Studio Code 的 launch.json 解析

    { "version": "0.2.0", "configurations": [ { "name": "(g ...

  7. 【问题解决:死锁】Lock wait timeout exceeded; try restarting transaction的问题

    执行数据删除操作时一直超时并弹出Lock wait timeout exceeded; try restarting transaction错误 解决办法 1.先查看数据库的事务隔离级别 select ...

  8. C# 截取 byte 字节 转字符串

    byte[] byteArray = System.Text.Encoding.Default.GetBytes(content); Byte[] ThisByte = new Byte[1];Buf ...

  9. Sample Classification Code of CIFAR-10 in Torch

    Sample Classification Code of CIFAR-10 in Torch from: http://torch.ch/blog/2015/07/30/cifar.html req ...

  10. LOJ 534 花团(线段树+dfs栈)

    题意 https://loj.ac/problem/534 思路 又是复杂度错误的一题,\(O(n^2\log n)\) 能过 \(15000\) . 虽然看起来强制在线,其实是一道假的在线题.首先按 ...