http://www.mysqltutorial.org/python-mysql-query/
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了http://www.mysqltutorial.org/python-mysql-query/,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含4539字,纯文字阅读大概需要7分钟。
内容图文
To query data in a MySQL database from Python, you need to do the following steps:
- Connect to the MySQL Database, you get a
MySQLConnection
object. - Instantiate a
MySQLCursor
object from the theMySQLConnection
object. - 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
MySQLConnection
object - Second, from the
MySQLConnection
object, we instantiated a newMySQLCursor
object - Third, we executed a query that selects all rows from the
books
table. - Fourth, we called
fetchone()
method to fetch the next row in the result set. In thewhile loop
block, 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/
标签:
本文系统来源:http://www.cnblogs.com/kungfupanda/p/5937320.html
内容总结
以上是互联网集市为您收集整理的http://www.mysqltutorial.org/python-mysql-query/全部内容,希望文章能够帮你解决http://www.mysqltutorial.org/python-mysql-query/所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。