python MySQLdb pymsql
参考文档 https://www.python.org/dev/peps/pep-0249/#nextset
本节内容
- MySQLdb
- pymysql
MySQLdb和pymysql分别为Python2和Python3操作MySQL数据库的模块,两个模块的用法基本相同, 这里就把两个模块放到一起说下用Python如何来操作MySQL数据库。
一.MySQLdb的使用
1.导入模块
import MySQLdb
2.建立连接,获取连接对象
在建立数据库连接时connect函数中可以接收多个参数,返回的为连接对象
connect参数说明如下↓
""" Create a connection to the database. It is strongly recommended
that you only use keyword parameters. Consult the MySQL C API
documentation for more information. host
string, host to connect user
string, user to connect as passwd
string, password to use db
string, database to use port
integer, TCP/IP port to connect to unix_socket
string, location of unix_socket to use conv
conversion dictionary, see MySQLdb.converters connect_timeout
number of seconds to wait before the connection attempt
fails. compress
if set, compression is enabled named_pipe
if set, a named pipe is used to connect (Windows only) init_command
command which is run once the connection is created read_default_file
file from which default client values are read read_default_group
configuration group to use from the default file cursorclass
class object, used to create cursors (keyword only) use_unicode
If True, text-like columns are returned as unicode objects
using the connection's character set. Otherwise, text-like
columns are returned as strings. columns are returned as
normal strings. Unicode objects will always be encoded to
the connection's character set regardless of this setting. charset
If supplied, the connection character set will be changed
to this character set (MySQL-4.1 and newer). This implies
use_unicode=True. sql_mode
If supplied, the session SQL mode will be changed to this
setting (MySQL-4.1 and newer). For more details and legal
values, see the MySQL documentation. client_flag
integer, flags to use or 0
(see MySQL docs or constants/CLIENTS.py) ssl
dictionary or mapping, contains SSL connection parameters;
see the MySQL documentation for more details
(mysql_ssl_set()). If this is set, and the client does not
support SSL, NotSupportedError will be raised. local_infile
integer, non-zero enables LOAD LOCAL INFILE; zero disables There are a number of undocumented, non-standard methods. See the
documentation for the MySQL C API for some hints on what they do. """
conn = MySQLdb.connect(host='192.168.10.165', port=3306, user='root', passwd='123456', db='center') # 和数据库建立连接
3.创建一个游标来进行数据库操作
游标默认返回的数据类型为tuple,当加入cursorclass=MySQLdb.cursors.DictCursor时,返回的数据类型为dict
cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
4.利用游标对象进行数据库操作
数据操作主要分为执行sql和返回数据
下面为cursor用来执行命令的方法:
callproc(self, procname, args) # 用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数
execute(self, query, args) # 执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数
executemany(self, query, args) # 执行单条sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
nextset(self) # 移动到下一个结果集
executemany处理过多的命令也不见得一定好,因为数据一起传入到server端,可能会造成server端的buffer溢出,而一次数据量过大,也有可能产生一些意想不到的麻烦。合理,分批次executemany是个不错的办法。
下面为cursor用来接收返回值的方法:
fetchall(self) # 接收全部的返回结果行.
fetchmany(self, size=None) # 接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.
fetchone(self) # 返回一条结果行.
scroll(self, value, mode='relative') # 移动指针到某一行.如果mode='relative',则表示从当前所在行移动value条,如果mode='absolute',则表示从结果集的第一行移动value条.
接下来看一完整的例子:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = '40kuai' import MySQLdb # 导入模块
conn = MySQLdb.connect(host='192.168.10.165', port=3306, user='root', passwd='123456', db='db') # 和数据库建立连接
cursor = conn.cursor() # 获取游标进行数据操作
# 查询
effect_row = cursor.executemany("select * from user limit %s ",(10,)) # 返回受影响行数
print effect_row # 返回为受影响的条数
print cursor.fetchone() # 打印一条返回结果
print ''.center(50,'#')
print cursor.fetchall() # 返回所有的数据,这里为剩余的数据
cursor.scroll(0,mode='absolute') # 重置游标位置
print cursor.fetchone() # 提交,不然无法保存新建或者修改的数据,这里为查询操作可以不写
conn.commit() # 关闭游标
cursor.close()
# 关闭连接
conn.close() # 输出(大概)
# 10
# (10001L,'40kuai',1476858893L)
# ##################################################
# ((10002L,'41kuai',1476858893L),......) # 后边数据省略
# (10001L,'40kuai',1476858893L)
5.对数据库进行操作时注意事项:
- 使用sql语句,这里要接收的参数都用%s占位符.要注意的是, 无论你要插入的数据是什么类型,占位符永远都要用%s
- param应该为tuple或者list
- 使用executemany添加多条数据时,每个传入参数的集合为一个tuple,整个参数组成一个tuple,或者list
- 返回数据为字典类型可以在创建数据库连接(connection)时传入cursorclass=MySQLdb.cursors.DictCursor,或者在创建游标时(cursor)加入参数cursorclass=MySQLdb.cursors.DictCursor
- --在conntction中加入cursorclass=MySQLdb.cursors.DictCursor会报错('module' object has no attribute 'cursors'),应该是有与对象还没有实例化没有cursors方法。
6.查询数据后的一些收尾工作
在对数据进行操作时需要说明两个函数,commit和rollback
如果使用支持事务的存储引擎,那么每次操作后,commit是必须的,否则不会真正写入数据库(查询操作可以不执行commit),对应rollback可以进行相应的回滚,但是commit后是无法再rollback的。commit() 可以在执行很多sql指令后再一次调用,这样可以适当提升性能。
# 需要分别的关闭指针对象和连接对象.他们有名字相同的方法
cursor.close()
conn.close()
编码:
Python文件设置编码 utf-8 (文件前面加上 #encoding=utf-8)
MySQL数据库charset=utf-8
Python连接MySQL是加上参数 charset=utf8
设置Python的默认编码为 utf-8 (sys.setdefaultencoding(utf-8)
7.一些例子
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = '40kuai'
import time
import MySQLdb # 导入模块 conn = MySQLdb.connect(host='192.168.10.165', port=3306, user='root', passwd='123456', db='db',
) # 和数据库建立连接
conn = set_charset('utf-8') # 设置字符集
cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) # 获取游标进行数据操作
# 删除表
cursor.execute('drop table if exists user')
cursor.execute('create table if not exists user(name varchar(128) primary key, created int(10))') # 添加
effect_row = cursor.execute("insert into user(name,created) values(%s,%s)",("40kuai",int(time.time())))
print 'insert',effect_row
# 添加多条
effect_row = cursor.executemany("insert into user(name,created) values(%s,%s)",(("41kuai",int(time.time())),("42kuai",int(time.time())),("43kuai",int(time.time()))))
print 'insert',effect_row
# 更新
effect_row = cursor.execute("update user set name=%s where created={time}".format(time=time.time()) ,('40kuai'))
print 'update',effect_row
# 查询
effect_row = cursor.execute("select * from user WHERE name='40kuai'")
print cursor.fetchone()
#删除
effect_row = cursor.execute("delete from user where name=%s" ,('40kuai'))
print 'delete',effect_row
# 查询
effect_row = cursor.execute("select * from user")
print cursor.fetchall() conn.commit() # 提交,不然无法保存新建或者修改的数据,这里为查询操作可以不写
cursor.close() # 关闭游标
conn.close() # 关闭连接
8.一些小知识点
- 如果有自增ID列通过 cursor.lastrowid 来获取最新自增ID
- 使用cursor.scroll(num,mode)来移动游标位置
- cursor.scroll(1,mode='relative') # 相对当前位置移动
- cursor.scroll(0,mode='absolute') # 相对绝对位置移动
二.pymysql的使用
pymysql是python3中操作mysql的模块,MySQLdb是python2中操作MySQL的模块,但在用法上和大同小异,这里只是说明下两者的不同
1.导入方法不同
正常人都可以理解
2.在对返回的数据设置为字典类型
pymysql: cursor
= conn.
cursor
(
cursor
=pymysql.cursors.DictCursor)
MySQLdb: cursor
= conn.
cursor
(
cursorclass
=pymysql.cursors.DictCursor)
其他的我也暂时还不知道,以后有的话我再补充。
python MySQLdb pymsql的更多相关文章
- Python MySQLdb在Linux下的快速安装
在家里windows环境下搞了一次 见 python MySQLdb在windows环境下的快速安装.问题解决方式 http://blog.csdn.NET/wklken/article/deta ...
- #MySQL for Python(MySQLdb) Note
#MySQL for Python(MySQLdb) Note #切记不要在python中创建表,只做增删改查即可. #步骤:(0)引用库 -->(1)创建连接 -->(2)创建游标 -- ...
- cygwin 下安装python MySQLdb
cygwin 下安装python MySQLdb 1) cygwin 更新 运行 cygwin/setup-x86_64.exe a 输入mysql,选择下面的包安装: libmysqlclient- ...
- Python MySQLdb模块连接操作mysql数据库实例_python
mysql是一个优秀的开源数据库,它现在的应用非常的广泛,因此很有必要简单的介绍一下用python操作mysql数据库的方法.python操作数据库需要安装一个第三方的模块,在http://mysql ...
- python MySQLdb在windows环境下的快速安装
python MySQLdb在windows环境下的快速安装.问题解决方式 使用python访问mysql,需要一系列安装 linux下MySQLdb安装见 Python MySQLdb在Linux下 ...
- windows 环境下安装python MySQLdb
使用Python访问MySQL,需要一系列安装 Linux下MySQLdb安装见 Python MySQLdb在Linux下的快速安装 http://blog.csdn.NET/wklken/arti ...
- python MySQLdb连接mysql失败(转载)
最近了解了一下django,数据库选用了mysql, 在连接数据库的过程中,遇到一点小问题,在这里记录一下,希望能够对遇到同样的问题的朋友有所帮助,少走一些弯路.关于django,想在这里也额外说一句 ...
- 117、python MySQLdb在windows环境下的快速安装、问题解决方式
使用Python访问MySQL,需要一系列安装 Linux下MySQLdb安装见 Python MySQLdb在Linux下的快速安装 http://blog.csdn.NET/wklken/arti ...
- python MySQLdb Windows下安装教程及问题解决方法(python2.7)
使用python访问mysql,需要一系列安装 linux下MySQLdb安装见 Python MySQLdb在Linux下的快速安装http://www.jb51.net/article/6574 ...
随机推荐
- python 人工智能资源推荐
原创 2017-06-05 玄魂工作室 玄魂工作室 我翻了翻我自己曾经看过的书,还是放弃了推荐.原因很简单,我对这个领域并不是很熟悉,我来推荐资源有点误人子弟.so,简单推点其他人建议给我的内容,希望 ...
- Zepto.js库touch模块代码解析
Zepto.js也许并不陌生,专门针对移动端开发,Zepto有一些基本的触摸事件可以用来做触摸屏交互(tap事件.swipe事件),Zepto是不支持IE浏览器的. 下面来解析一些Zepto.js触摸 ...
- js回顾(DOM中标签的CRUD,表格等)
01-DOM中的创建和添加标签 02-删除替换克隆标签 03-全选全不选反选 04-新闻字体 05-表格增删 06-动态生成表格 07-表格隔行变色 08-左到右右到左(将左边的标签移动到右边) 09 ...
- 分布式服务框架HSF
最近在读阿里巴巴中台战略思想与架构这本书,so和大家分享一些我get到的东东. HSF是阿里巴巴内部的分布式服务框架,这个大家都很熟悉了,先上一张HSF的工作原理图: 这个图说明了HSF框架中每个组件 ...
- Android开发——发布第三方库到JitPack上
前言: 看到大神们的写的第三方控件,比较好用,我们使用的时候直接是在gradle上加上代码就可以使用了,现在到我们写了一个第三方控件,想要别人使用的时候也是直接在gradle加上相关的代码就可以用了, ...
- express实践(一)
涉及以下这些内容: 主体. cookie.session 数据 模板引擎 服务器基本结构: const express=require('express'); const static=require ...
- python中的进程池:multiprocessing.Pool()
python中的进程池: 我们可以写出自己希望进程帮助我们完成的任务,然后把任务批量交给进程池 进程池帮助我们创建进程完成任务,不需要我们管理.进程池:利用multiprocessing 下的Pool ...
- 【WebGL入门】画一个旋转的cube
最近搜罗了各种资料,发现WebGL中文网特别好用,很适合新手入门:http://www.hewebgl.com/article/getarticle/50 只需要下载好需要的所有包,然后用notepa ...
- linux添加硬盘分区挂载教程
基本步骤:分区--格式化--挂载--写入文件 1.首先用fdisk -l命令查看添加的硬盘名称,可以看到sdb为新增的硬盘 [root@oracle ~]# fdisk -l Disk /dev/sd ...
- 高下相倾,前后相随——iterator 与 for ... of 循环
iterator 是es6新提供的一种遍历器.本质上是一个接口,为各种不同的数据结构,提供统一的访问机制. 数据只要部署了iterator接口,便是可遍历的数据,标志是具有Symbol.iterato ...