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:

  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()

时间: 2024-10-03 18:58:49

http://www.mysqltutorial.org/python-mysql-query/的相关文章

Python/MySQL表操作以及连接

Python/MySQL表操作以及连接 mysql表操作: 主键:一个表只能有一个主键.主键可以由多列组成. mysql> create table yuan(id int auto_increment,yuangongname int,bumen_id int, primary key(id,yuangongname))engine=innodb default charset=utf8; Query OK, 0 rows affected (0.43 sec) 外键 :可以进行联合外键,操作

在MySQL query browser中要导出execl表单

导出:  在MySQL query browser中要导出execl表单,只需要点击file,选择export execl就可以了(要先进入表单哦!). 导入: 数据库的数据太多一下导入有点麻烦,如何将excel的数据直接导入数据库呢? 第一步 另存为txt文档,名字最好为数据库的table名.  在这我们要保存问文本文件用制表符分割的那个,这样我们的数据就不会乱. 第二步 打开txt文档,点击另存为,修改编码,解决中文utf8.  这个时候的文件名必须和你要导入的table名称一样,否则在lo

python mysql模块

#!/usr/bin/python import MySQLdb def new_mail_mysql(ak): print ak conn=MySQLdb.connect(host='m3306.sae.sina.com.cn',user='sae_ol',passwd='7b149edb22ae7526',db='sae',port=3306) cur=conn.cursor() sql="select name from app where accesskey='%s'"%ak

Python/MySQL(三、pymysql使用)

Python/MySQL(三.pymysql使用) 所谓pymysql就是通过pycharm导入pymysql模块进行远程连接mysql服务端进行数据管理操作. 一.在pycharm中导入pymysql模块: 最后进行搜索和导入 二.通过pycharm语句连接MySQ服务端(MySQL服务端必须先启动) 1 import pymysql 2 导入pymysql 3 conn=pymysql.connect(host='localhost',user='root',password='guobao

python+ mysql存储二进制流的方式

很多时候我们为了管理方便会把依稀很小的图片存入数据库,有人可能会想这样会不会对数据库造成很大的压力,其实大家可以不用担心,因为我说过了,是存储一些很小的图片,几K的,没有问题的! 再者,在这里我们是想讲一种方法,python+ mysql存储二进制流的方式 这里用的是Mysqldb,python里面最常用的数据库模块 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 28 29 30 31 32 33

Python+Mysql生成zabbix统计数据

先大概了解一下zabbix数据库结构: 1.groups表 可以根据组名查到组ID 2.找到组ID就可以根据组ID找出这个组下面的所有服务器的ID,这个关系在hosts_groups表里面: 3.有了hostid就可以在hosts表里查看这台机器的基本信息了: items表则可以根据hostid查出这台服务器的所有监控项: 4.终于在items表查到itemid,利用这个itemid在trends和trends_uint这两个表中统计出我们需要的数据 我python水平挺菜的,很多面向对象的功能

Python&MySQL操作过程中遇到的编码问题

对于Python字符编码的理解 之前整理了一部分,这次主要是设计到数据库操作的. 下面是一些编码方面的概念和原理,以条目方式整理: CREATE DATABASE IF NOT EXISTS db_name DEFAULT CHARSET utf8 COLLATE utf8_general_ci; DEFAULT CHARSET是设置默认字符编码集,也就是数据在库内从存储编码,我的理解是在存储这个层面上的,如果SQL命令是以gbk方式传输数据的(cur.execute('SET NAMES ut

在mac OS X中配置python mysql开发环境

1. 首先要下载安装mysql,下载地址: http://cdn.mysql.com/Downloads/MySQL-5.6/mysql-5.6.19.tar.gz 解压: tar -xzvf mysql-5.6.19.tar.gz 然后下载gmock,编译mysql时需要用到: https://googlemock.googlecode.com/files/gmock-1.7.0.zip 解压到指定目录 <span style="font-size:14px;">unzi

第一节、Alex 讲解 python+mysql 交互;

Python Mysql 交互 A.Alex 的语法展示: import MySQLdb  try: conn=MySQL.connect(host='localhost',user='root',passwod='123qwe',db='test-DB',port='3306') cur =conn.cursor() cur.execute('select * from user_info') cur.close() conn.close() except MySQLdb.Errot,e: p

Python&mdash;&gt;Mysql&mdash;&gt;Dbvisualizer

1.Download Connector/Python:mysql-connector-python-2.1.3-py2.7-win32 Mysql:mysql-installer-community-5.5.48.0 Python:python-2.7.10 2.安装好Python,Mysql Connector/Python:  http://dev.mysql.com/doc/connector-python/en/connector-python-installation.html Py