http://www.mysqltutorial.org/python-mysql-query/
This tutorial shows you how to query data from a MySQL database in Python by using MySQL Connector/Python API such as fetchone() , fetchmany() , and fetchall() .
To query data in a MySQL database from Python, you need to do the following steps:
- Connect to the MySQL Database, you get a
MySQLConnectionobject. - Instantiate a
MySQLCursorobject from the theMySQLConnectionobject. - Use the cursor to execute a query by calling its
execute()method. - Use
fetchone(),fetchmany()orfetchall()method to fetch data from the result set. - Close the cursor as well as the database connection by calling the
close()method of the corresponding object.
We will show you how to use fetchone() , fetchmany() , and fetchall() methods in more detail in the following sections.
Querying data with fetchone
The fetchone() method returns the next row of a query result set or None in case there is no row left. Let’s take a look at the following code:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
def query_with_fetchone():
try:
dbconfig = read_db_config()
conn = MySQLConnection(**dbconfig)
cursor = conn.cursor()
cursor.execute("SELECT * FROM books")
row = cursor.fetchone()
while row is not None:
print(row)
row = cursor.fetchone()
except Error as e:
print(e)
finally:
cursor.close()
conn.close()
if __name__ == '__main__':
query_with_fetchone()
|
Let’s examine the code in detail:
- First, we connected to the database by create a new
MySQLConnectionobject - Second, from the
MySQLConnectionobject, we instantiated a newMySQLCursorobject - Third, we executed a query that selects all rows from the
bookstable. - Fourth, we called
fetchone()method to fetch the next row in the result set. In thewhile loopblock, we printed out the content of the row and move to the next row until all rows are fetched. - Fifth, we closed both cursor and connection objects by invoking the
close()method of the corresponding object.
Querying data with fetchall
In case the number of rows in the table is small, you can use the fetchall() method to fetch all rows from the database table. See the following code.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
def query_with_fetchall():
try:
dbconfig = read_db_config()
conn = MySQLConnection(**dbconfig)
cursor = conn.cursor()
cursor.execute("SELECT * FROM books")
rows = cursor.fetchall()
print('Total Row(s):', cursor.rowcount)
for row in rows:
print(row)
except Error as e:
print(e)
finally:
cursor.close()
conn.close()
if __name__ == '__main__':
query_with_fetchall()
|
The logic is similar to the example with the fetchone() method except for the fetchall()method call part. Because we fetched all rows from the books table into the memory, we can get the total rows returned by using the rowcount property of the cursor object.
Querying data with fetchmany
For a relatively big table, it takes time to fetch all rows and return the result set. In addition, fetchall() needs to allocate enough memory to store the entire result set in the memory. This is inefficient and not a good practice.
MySQL Connector/Python provides us with the fetchmany() method that returns the next number of rows (n) of the result set, which allows us to balance between time and memory space. Let’s take a look at how do we use fetchmany() method.
First, we develop a generator that chunks the database calls into a series of fetchmany() calls as follows:
|
1
2
3
4
5
6
7
|
def iter_row(cursor, size=10):
while True:
rows = cursor.fetchmany(size)
if not rows:
break
for row in rows:
yield row
|
Second, we can use the iter_row() generator to fetch 10 rows at a time as shown below:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
def query_with_fetchmany():
try:
dbconfig = read_db_config()
conn = MySQLConnection(**dbconfig)
cursor = conn.cursor()
cursor.execute("SELECT * FROM books")
for row in iter_row(cursor, 10):
print(row)
except Error as e:
print(e)
finally:
cursor.close()
conn.close()
|
http://www.mysqltutorial.org/python-mysql-query/的更多相关文章
- Python Mysql 篇
Python 操作 Mysql 模块的安装 linux: yum install MySQL-python window: http://files.cnblogs.com/files/wupeiqi ...
- python 之路,Day11(上) - python mysql and ORM
python 之路,Day11 - python mysql and ORM 本节内容 数据库介绍 mysql 数据库安装使用 mysql管理 mysql 数据类型 常用mysql命令 创建数据库 ...
- Python/MySQL(一、基础)
Python/MySQL(一.基础) mysql: MYSQL : 是用于管理文件的一个软件 -socket服务端 (先启动) -本地文件操作 -解析 指令[SQL语句] -客户端软件 (各种各样的客 ...
- Python/MySQL(二、表操作以及连接)
Python/MySQL(二.表操作以及连接) mysql表操作: 主键:一个表只能有一个主键.主键可以由多列组成. 外键 :可以进行联合外键,操作. mysql> create table y ...
- python/MySQL(索引、执行计划、BDA、分页)
---恢复内容开始--- python/MySQL(索引.执行计划.BDA.分页) MySQL索引: 所谓索引的就是具有(约束和加速查找的一种方式) 创建索引的缺点是对数据进行(修改.更新.删除) ...
- Discuz! X3搬家后UCenter出现UCenter info: MySQL Query Error解决方案
Discuz! X3 X2.5论坛搬家后 登录UCenter出现报错:UCenter info: MySQL Query ErrorSQL:SELECT value FROM [Table]vars ...
- Python—>Mysql—>Dbvisualizer
MySQLdb: https://pypi.python.org/pypi/MySQL-python/1.2.4 import MySQLdb 1.Download Connector/Python: ...
- MySQL Query Profile
MySQL Query Profiler, 可以查询到此 SQL 语句会执行多少, 并看出 CPU/Memory 使用量, 执行过程 System lock, Table lock 花多少时间等等.从 ...
- Python MySQL ORM QuickORM hacking
# coding: utf-8 # # Python MySQL ORM QuickORM hacking # 说明: # 以前仅仅是知道有ORM的存在,但是对ORM这个东西内部工作原理不是很清楚, ...
- 树莓派安装ubuntu-server,配置镜像,安装python/mysql/samba记录
目标: 1/在raspberrypi 3B上安装ubuntu-server 2/配置好python/mysql/samba等服务,实现爬虫稳定运行我的硬件准备: 1/raspberrypi 3B 2/ ...
随机推荐
- [开源]基于WPF实现的Gif图片分割器,提取GIf图片中的每一帧
不知不觉又半个月没有更新博客了,今天终于抽出点时间,来分享一下前段时间的成果. 在网上,我们经常看到各种各样的图片,尤其是GIF图片的动态效果,让整个网站更加富有表现力!有时候,我们看到一些比较好看的 ...
- Alljoyn瘦客户端库介绍(官方文档翻译)
Alljoyn瘦客户端库介绍(上) 1.简介 本文档对AllJoynTM瘦客户端的核心库文件(AJTCL)进行了详尽的介绍.本文档介绍了系统整体架构,AllJoyn框架结构,并着重于介绍如何将嵌入式设 ...
- [转]GC简介
[转]GC简介 原文链接:http://www.cnblogs.com/cposture/p/4845189.html 原文写得太好了,这里转一下. 1 GC机制 1.1 对象 从计算机的角度,装有数 ...
- JavaScript面试时候的坑洼沟洄——数据类型
前些日子写了篇关于最近找工作的一些感受的博客 找工作的一些感悟--前端小菜的成长,没想到得到了很多园友的共鸣,得到了很多鼓励,也有园友希望我分享一些笔试.面试的经验.我觉得分享一些笔试题没太多价值,对 ...
- Bootstrap 3的box-sizing样式导致UEditor控件的图片无法正常缩放
UEditor组件是百度提供的一套开源的web在线所见即所得富文本编辑器,具有轻量,可定制,注重用户体验等特点,基于MIT协议,功能很强大.最近在使用的过程中发现其中上传的图片(或者插入已有的表情包图 ...
- linux添加自定义的命令!
修改了/root/下的.bashrc -bash-4.1# vi .bashrc # .bashrc # User specific aliases and functions alias rm='r ...
- 详解 JavaScript的 call() 和 apply()
定义 ECMAScript规范为所有函数都包含两个方法(这两个方法非继承而来), call 和 apply .这两个函数都是在特定的作用域中调用函数,能改变函数的作用域,实际上是改变函数体内 this ...
- DAC Usage2:通过DAC实现DB Schema的Migration和Upgrade
一,Introduce Extract DAC 是从现存的DB中创建DAC,抽取DB Object的definition 和 与之相关的实例级别的元素,比如Login,以及Login 和User之间的 ...
- ExtJS面向对象
序言 1.ExtJs是一套很好的后台框架.现在很流行的,我们要会. 2.这是我写ExtJs的第一篇,以后会写很多直到把这框架运用的炉火纯青,走火入魔. ExtJs中的命名空间 我是做.net的,这命名 ...
- Python第一天 - set
(一)初识set dict的作用是建立一组 key 和一组 value 的映射关系,dict的key是不能重复的.有的时候,我们只想要 dict 的 key,不关心 key 对应的 value,目的就 ...