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/ ...
随机推荐
- 企业IT管理员IE11升级指南【2】—— Internet Explorer 11 对Adobe Flash的支持
企业IT管理员IE11升级指南 系列: [1]—— Internet Explorer 11增强保护模式 (EPM) 介绍 [2]—— Internet Explorer 11 对Adobe Flas ...
- 浅析MSIL中间语言——PE文件结构篇
一.开篇 开篇我想讲一下于本文无关的话题,其实我很想美化一下自己博客园一直没时间弄,无意间找了博客园李宝亨的博客园里面有一篇分享自己主题的文章,我就将这个模板暂时用作我的blog主题,我要讲述一个关于 ...
- Npm install failed with “cannot run in wd”
Linux环境下,root账户,安装某些npm包的时候报下面的错误,例如安装grunt-contrib-imagemin时: Error: EACCES, mkdir '/usr/local/lib/ ...
- rem单位和em单位的使用
今天弄了一点响应式的东西,本以为很快就可以弄好,结果还是绕晕了头,所以还是写下来方便下次看吧! 一开始我打算用百分比%来做响应式布局,后来算的很懵圈,就果断放弃了,哈哈是不是很明智. 接下来就是rem ...
- Redis命令笔记
一.string类型:(1)set :设置key对应的值为string类型的value,例:set name helloworld(2)get :获取key对应的值为string类型的value,例: ...
- Sql Server系列:Transact-SQL变量
变量是Transact-SQL中由用户定义.可对其赋值并参与运算的一个实体,分为全局变量和局部变量.其中全局变量由系统自定义并维护,全局变量名称前面有@@字符,任何程序均可随时调用.局部变量名称前面有 ...
- 【WP 8.1开发】如何动态生成Gif动画
相信如何为gif文件编码,很多朋友都会,而难点在于怎么让GIF文件中的帧动起来,也就是创建gif动画. Gif文件编码方法 先简单介绍一下编码的方法. 1.调用BitmapEncoder.Create ...
- Undo/Redo for Qt Tree Model
Undo/Redo for Qt Tree Model eryar@163.com Abstract. Qt contains a set of item view classes that use ...
- MySQL学习笔记一:常用显示命令
1.开启和关闭MySQL服务 WIN平台:NET START MYSQL55 :NET STOP MYSQL55 Linux平台:service mysql start : service mysql ...
- .Net处理Oracle中Clob类型字段总结
最近在做项目中用到Clob这个字段,Clob是存储无限长字符的Oracle字段,用的时候网上找资料找了好久,内容不是很多,大部分都不能用,当然也有可以用的,测试了不同版本,整理了一下,给大家在做项目的 ...