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')
Python2 - MySQL适配器 MySQLdb的更多相关文章
- Python3 - MySQL适配器 PyMySQL
本文我们为大家介绍 Python3 使用 PyMySQL 连接数据库,并实现简单的增删改查. 什么是 PyMySQL? PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一 ...
- python2.7中MySQLdb的安装与使用详解
Python2.7中MySQLdb的使用 import MySQLdb #1.建立连接 connect = MySQLdb.connect( '127.0.0.1', #数据库地址 'root', # ...
- Python与数据库[1] -> 数据库接口/DB-API[1] -> MySQL 适配器
MySQL适配器 / MySQL Adapter MySQL是一种关系型数据库,下面主要介绍利用如何利用Python的MySQL适配器来对MySQL进行操作,其余内容可参考文末相关阅读. 1 MySQ ...
- 快速熟悉python 下使用mysql(MySQLdb)
首先你需要安装上mysql和MySQLdb模块(当然还有其他模块可以用),这里我就略过了,如果遇到问题自行百度(或者评论在下面我可以帮忙看看) 这里简单记录一下自己使用的学习过程: 一.连接数据库 M ...
- python2.7之MySQLdb模块 for linux安装
1.下载:MySQL-pythonhttp://sourceforge.net/projects/mysql-python/files/mysql-python-test/1.2.3b1/MySQL- ...
- Ubuntu安装Mysql+Django+MySQLdb
安装Mysql sudo apt-get install mysql-server mysql-client root@IdeaPad:/# mysql -u root -p Enter passwo ...
- 【mysql】MySQLdb中的事务处理
MySQL数据库有一个自动提交事务的概念,autocommit.含义是,如果开启autocommit, 则每一个语句执行后会自动提交.即一个语句视为一个事务. 在python使用的MySQLdb中,默 ...
- windows环境python2.7安装MySQLdb
我电脑是64位,并且安装python不是默认路径,使用pip和mysql-python的exe文件安装都失败了. 后在网上找到一种安装方法,记录下. 确保安装了wheel,我的2.7默认安装了 pip ...
- 【mysql】MySQLdb返回字典方法
来源:http://blog.csdn.net/zgl_dm/article/details/8710371 默认mysqldb返回的是元组,这样对使用者不太友好,也不利于维护下面是解决方法 impo ...
随机推荐
- request 模块详细介绍
request 模块详细介绍 request Requests 是使用 Apache2 Licensed 许可证的 基于Python开发的HTTP 库,其在Python内置模块的基础上进行了高度的封装 ...
- intel webrtc 部署
org link conference server Configure the MCU server 1. set the maximum numbers of open files, runnin ...
- EXP7 网络欺诈技术防范(修改版)
实践内容 本实践的目标理解常用网络欺诈背后的原理,以提高防范意识,并提出具体防范方法. 1.简单应用SET工具建立冒名网站 2.ettercap DNS spoof 3.结合应用两种技术,用DNS s ...
- hdu 1394 Minimum Inversion Number - 树状数组
The inversion number of a given number sequence a1, a2, ..., an is the number of pairs (ai, aj) that ...
- 【Python020--内嵌函数和闭包】
一.内嵌函数&闭包 1.最好是访问全局变量而不是修改全局变量,修改全局变量Python会内部屏蔽(修改后,函数会内部创建一个和全局变量一抹一样的变量) >>> count = ...
- 给sublime设置格式化代码的快捷键
sublime中自建的有格式化按钮: Edit -> Line -> Reindent 只是sublime并没有给他赋予快捷键,所以只需加上快捷键即可 Preference -& ...
- Restful framework【第四篇】视图组件
基本使用 -view的封装过程有空可以看一下 -ViewSetMixin # ViewSetMixin 写在前面,先找ViewSetMixin的as_view方法 # 用了ViewSetMixin , ...
- P4137 Rmq Problem / mex
目录 链接 思路 线段树 莫队 链接 https://www.luogu.org/problemnew/show/P4137 思路 做了好几次,每次都得想一会,再记录一下 可持久化权值线段树 区间出现 ...
- 密码发生器|2012年蓝桥杯B组题解析第八题-fishers
(10')密码发生器 在对银行账户等重要权限设置密码的时候,我们常常遇到这样的烦恼:如果为了好记用生日吧,容易被破解,不安全:如果设置不好记的密码,又担心自己也会忘记:如果写在纸上,担心纸张被别人发现 ...
- 奇怪的比赛|2012年蓝桥杯B组题解析第四题-fishers
(8')奇怪的比赛 某电视台举办了低碳生活大奖赛.题目的计分规则相当奇怪: 每位选手需要回答10个问题(其编号为1到10),越后面越有难度.答对的,当前分数翻倍:答错了则扣掉与题号相同的分数(选手必须 ...