Mysql queries in python

Python MySQL Select From

To select from a table in MySQL, use the «SELECT» statement:

Example

Select all records from the «customers» table, and display the result:

mydb = mysql.connector.connect(
host=»localhost»,
user=»yourusername«,
password=»yourpassword«,
database=»mydatabase»
)

mycursor.execute(«SELECT * FROM customers»)

Note: We use the fetchall() method, which fetches all rows from the last executed statement.

Selecting Columns

To select only some of the columns in a table, use the «SELECT» statement followed by the column name(s):

Example

Select only the name and address columns:

mydb = mysql.connector.connect(
host=»localhost»,
user=»yourusername«,
password=»yourpassword«,
database=»mydatabase»
)

mycursor.execute(«SELECT name, address FROM customers»)

Using the fetchone() Method

If you are only interested in one row, you can use the fetchone() method.

The fetchone() method will return the first row of the result:

Example

mydb = mysql.connector.connect(
host=»localhost»,
user=»yourusername«,
password=»yourpassword«,
database=»mydatabase»
)

mycursor.execute(«SELECT * FROM customers»)

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Python MySQL – Query Data from a Table in Python

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

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:

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()Code language: Python (python)

Let’s examine the code in detail:

  1. First, connect to the database by creating a new MySQLConnection object
  2. Next, instantiate a new MySQLCursor object from the MySQLConnection object
  3. Then, execute a query that selects all rows from the books table.
  4. After that, fetch the next row in the result set by calling the fetchone() . In the while loop block, display the contents of the row and move to the next row until all rows are fetched.
  5. Finally, close both cursor and connection objects by invoking the close() method of the corresponding object.

Notice that we used the function read_db_config() from the module python_mysql_dbconfig.py that we created in the connecting to MySQL database tutorial.

Querying data with fetchall() method

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.

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()Code language: Python (python)

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

For a relatively big table, it takes time to fetch all rows and return the entire result set. In addition, fetchall() needs to allocate enough memory to store the entire result set in the memory, which is not efficient.

MySQL Connector/Python has the fetchmany() method that returns the next number of rows (n) of the result set, which allows you to balance between retrieval time and memory space.

First, develop a generator that chunks the database calls into a series of fetchmany() calls:

def iter_row(cursor, size=10): while True: rows = cursor.fetchmany(size) if not rows: break for row in rows: yield rowCode language: Python (python)

Second, use the iter_row() generator to fetch 10 rows at a time :

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()Code language: Python (python)

In this tutorial, you have learned various ways to query data from the MySQL database in Python. It is important to understand each technique by balancing between time to retrieve data and memory needed for storing the result set.

Источник

Читайте также:  Html creating buttons link
Оцените статью