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:

  1. Connect to the MySQL Database, you get a MySQLConnection object.
  2. Instantiate a  MySQLCursor object from the the MySQLConnection object.
  3. Use the cursor to execute a query by calling its  execute() method.
  4. Use fetchone() ,  fetchmany() or  fetchall() method to fetch data from the result set.
  5. 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:

  1. First, we connected to the database by create a new  MySQLConnection object
  2. Second, from the  MySQLConnection object, we instantiated a new  MySQLCursor object
  3. Third, we executed a query that selects all rows from the books table.
  4. Fourth, we called  fetchone() method to fetch the next row in the result set. In the  while loop block, we printed out the content of the row and move to the next row until all rows are fetched.
  5. 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/的更多相关文章

  1. Python Mysql 篇

    Python 操作 Mysql 模块的安装 linux: yum install MySQL-python window: http://files.cnblogs.com/files/wupeiqi ...

  2. python 之路,Day11(上) - python mysql and ORM

    python 之路,Day11 - python mysql and ORM   本节内容 数据库介绍 mysql 数据库安装使用 mysql管理 mysql 数据类型 常用mysql命令 创建数据库 ...

  3. Python/MySQL(一、基础)

    Python/MySQL(一.基础) mysql: MYSQL : 是用于管理文件的一个软件 -socket服务端 (先启动) -本地文件操作 -解析 指令[SQL语句] -客户端软件 (各种各样的客 ...

  4. Python/MySQL(二、表操作以及连接)

    Python/MySQL(二.表操作以及连接) mysql表操作: 主键:一个表只能有一个主键.主键可以由多列组成. 外键 :可以进行联合外键,操作. mysql> create table y ...

  5. python/MySQL(索引、执行计划、BDA、分页)

    ---恢复内容开始--- python/MySQL(索引.执行计划.BDA.分页) MySQL索引: 所谓索引的就是具有(约束和加速查找的一种方式)   创建索引的缺点是对数据进行(修改.更新.删除) ...

  6. Discuz! X3搬家后UCenter出现UCenter info: MySQL Query Error解决方案

    Discuz! X3 X2.5论坛搬家后 登录UCenter出现报错:UCenter info: MySQL Query ErrorSQL:SELECT value FROM [Table]vars ...

  7. Python—>Mysql—>Dbvisualizer

    MySQLdb: https://pypi.python.org/pypi/MySQL-python/1.2.4 import MySQLdb 1.Download Connector/Python: ...

  8. MySQL Query Profile

    MySQL Query Profiler, 可以查询到此 SQL 语句会执行多少, 并看出 CPU/Memory 使用量, 执行过程 System lock, Table lock 花多少时间等等.从 ...

  9. Python MySQL ORM QuickORM hacking

    # coding: utf-8 # # Python MySQL ORM QuickORM hacking # 说明: # 以前仅仅是知道有ORM的存在,但是对ORM这个东西内部工作原理不是很清楚, ...

  10. 树莓派安装ubuntu-server,配置镜像,安装python/mysql/samba记录

    目标: 1/在raspberrypi 3B上安装ubuntu-server 2/配置好python/mysql/samba等服务,实现爬虫稳定运行我的硬件准备: 1/raspberrypi 3B 2/ ...

随机推荐

  1. sqlalchemy(一)基本操作

    sqlalchemy(一)基本操作 sqlalchemy采用简单的Python语言,为高效和高性能的数据库访问设计,实现了完整的企业级持久模型. 安装 需要安装MySQLdb pip install ...

  2. 【原】通过JS打开IE新tab(非Window)的解决方案

    近日项目里遇到限定在IE的tab窗口里打开新窗口的需求,结合网上的资源和亲自实践,总结以下比较可行的解决方案. 1.首先必须保证IE的设置正确.打开IE的Internet options ->G ...

  3. JS中script词法分析

    核心:JS中的script是分段执行的. <script> var i = 10; </script> <script> alert(i); </script ...

  4. UpdateData(TRUE)与UpdateData(FALSE)的使用

    二者是更新对话框的控件与变量. 1.先要建立对应关系 如 编辑框IDC_Edit  和 变量 m_name DDX_Text(pDX, IDC_EDIT, m_name); 2.若是在编辑框输入名字 ...

  5. 在UWP中页面滑动导航栏置顶

    最近在研究掌上英雄联盟,主要是用来给自己看新闻,顺便copy个界面改一下段位装装逼,可是在我copy的时候发现这个东西 当你滑动到一定距离的时候导航栏会置顶不动,这个特性在微博和淘宝都有,我看了@ms ...

  6. JS原生基础终结篇 (帅哥)

    闭包 基础    面向对象基础 1.1 闭包 在程序语言中,所谓闭包,是指语法域位于某个特定的区域,具有持续参照(读写)位于该区域内自身范围之外的执行域上的非持久型变量值能力的段落.这些外部执行域的非 ...

  7. Entity Framework Code First添加修改及删除单独实体

    对于一个单独实体的通常操作有3种:添加新的实体.修改实体以及删除实体. 1.添加新的实体 Entity Framework Code First添加新的实体通过调用DbSet.Add()方法来实现. ...

  8. 深入理解脚本化CSS系列第一篇——脚本化行内样式

    × 目录 [1]用法 [2]属性 [3]方法 前面的话 脚本化CSS,通俗点说,就是使用javascript来操作CSS.引入CSS有3种方式:外部样式,内部样式和行间样式.本文将主要介绍脚本化行间样 ...

  9. java中volatile关键字

    一.前言 JMM提供了volatile变量定义.final.synchronized块来保证可见性. 用volatile修饰的变量,线程在每次使用变量的时候,都会读取变量修改后的最的值.volatil ...

  10. TortoiseGit与github实现项目的上传

    1. 下载并安装相关软件 这里主要涉及的软件包括msysgit和TortoiseGit. msysgit的下载地址:http://msysgit.googlecode.com/files/Git-1. ...