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/ ...
随机推荐
- Redis系列(五)-Opserver的监控
阅读目录: 基本介绍 使用配置 部署实例 面板属性 基本介绍 Opserver是Stack Exchange的一个开源监控系统,基于Net.MVC开发,所以Net程序员可以轻松基于它二次开发.它主要监 ...
- Redis系列(二)-Hredis客户端设计及开源
接上篇c#实现redis客户端(一),重新整理些了下. 阅读目录: 项目说明 Hredis设计图 单元测试场景 总结 项目说明 背景:因为有地方要用,而又没找到对sentinel良好支持的Net客户端 ...
- MySQL 远程连接(federated存储引擎)
标签:federated存储引擎 概述 本文主要介绍通过federated存储引擎建立远程连接表 测试环境:mysql 5.6.21 步骤 开启federated存储引擎 先查看federated存储 ...
- 激活jws.mono的图像处理
不得不说,jws.mono真的给我们带来了很大的便利,它免除了我们编译Linux.NET所带来的烦恼,节省了我们的时间.但是金无足赤人无完人,虽然jws.mono已经大致能够提供与我们自行编译相同的效 ...
- ASP.NET MVC 5 - 将数据从控制器传递给视图
在我们讨论数据库和数据模型之前,让我们先讨论一下如何将数据从控制器传递给视图.控制器类将响应请求来的URL.控制器类是给您写代码来处理传入请求的地方,并从数据库中检索数据,并最终决定什么类型的返回结果 ...
- Spark DAGSheduler生成Stage过程分析实验
RDD.Action触发SparkContext.run,这里举最简单的例子rdd.count() /** * Return the number of elements in the RDD. */ ...
- 3.用Redis Desktop Manager连接Redis
Redis Desktop Manager是Redis图形化管理工具,方便管理人员更方便直观地管理Redis数据. 然而在使用Redis Desktop Manager之前,有几个要素需要注意: 一. ...
- 设有一数据库,包括四个表:学生表(Student)、课程表(Course)、成绩表(Score)以及教师信息表(Teacher)。
一. 设有一数据库,包括四个表:学生表(Student).课程表(Course).成绩表(Score)以及教师信息表(Teacher).四个表的结构分别如表1-1的表(一)~表( ...
- 基于stm32f4的ucGUI通过外部flash存储汉字库显示任意英文字符和汉字组合(控件可用)
在做一个用到ucGUI的项目的时候要用到不定的汉字和英文字符,但是ucGUI本身又不支持读取芯片外部flash的字库来显示,于是查了下资料,如下: http://www.cnblogs.com/hik ...
- The transaction log for database 'xxxx' is full due to 'ACTIVE_TRANSACTION'
今天查看Job的History,发现Job 运行失败,错误信息是:“The transaction log for database 'xxxx' is full due to 'ACTIVE_TRA ...