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/ ...
随机推荐
- 译文---C#堆VS栈(Part One)
前言 本文主要是讲解C#语言在内存中堆.栈的使用情况,使读者能更好的理解值类型.引用类型以及线程栈.托管堆. 首先感谢原文作者:Matthew Cochran 为我们带来了一篇非常好的文章,并配以大量 ...
- java中文乱码解决之道(八)-----解决URL中文乱码问题
我们主要通过两种形式提交向服务器发送请求:URL.表单.而表单形式一般都不会出现乱码问题,乱码问题主要是在URL上面.通过前面几篇博客的介绍我们知道URL向服务器发送请求编码过程实在是实在太混乱了.不 ...
- MyEclipse打开 HTML 报错Failed to create the part's controls
拷贝代码时有时会弹出这个错误,页面仍然可以访问,但是无法编辑很郁闷. MyEclipse默认打开编辑页面是MyEclipse visual html designer 右击html页面选择open ...
- 【敏捷开发】Android团队开发规范
这里说的开发规范分成目录规范,项目和包名的命名规范,类,方法,变量和常量的命名规范这几种. 目录规范 目录规范——在开发中整体文件夹组织结构. Requirement——需求文档文件夹 Design— ...
- 关于CefSharp的坎坷之路
项目背景: 公司的XX产品需要升级和以后支持多平台的使用.因为之前项目是由WPF实现的.目前以后想作为Html5来展示页面. 因为涉及到整体更改遇到的问题较多以及其他原因,所以只是内部内容区域先替换为 ...
- salesforce 零基础学习(五十)自定义View或者List以及查看系统原来的View或者List
salesforce给我们提供了标准的页面,比如标准的页面包括标准的列表和标准的详细页视图.有的时候我们想要自定义视图,比如做一个项目的时候不希望使用者直接通过ID查看到标准的详细页,而是跳转到指定处 ...
- JS函数 -- 功能,语法,返回值,匿名函数,自调用匿名函数,全局变量与局部变量,arguments的使用
“JavaScript设计得最出色的就是它的函数的实现.” -- <JavaScript语言精粹> 函数包含一组语句,它们是JS的基础模块单元,用于指定对象的行为.一般来说,所谓编程,就是 ...
- 详解CSS的相对定位和绝对定位
CSS的相对定位和绝对定位通常情况下,我们元素的position属性的值默认为static 就是没有定位,元素出现在正常的文档流中,,这个时候你给这个元素设置的left,right,bottom,to ...
- 虚拟文件系统(VFS)
原文链接:http://www.orlion.ga/1008/ linux在不同的文件系统之上做了一个抽象层,使得文件.目录.读写访问等概念都成为抽象层概念,这个抽象层被称为虚拟文件系统(VFS). ...
- Vue 方法与事件处理器
按键修饰符 在监听键盘事件时,我们经常需要检测 keyCode.Vue.js 允许为 v-on 添加按键修饰符: <!-- 只有在 keyCode 是 时调用 vm.submit() --> ...