Python2 - MySQL适配器 MySQLdb

本文实例讲述了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')

 

posted @ 2017-09-20 08:02  Blue·Sky  阅读(548)  评论(0编辑  收藏  举报