The cursor.fetchone()
method in Python is used to fetch the next row of a query result set, returning a single row as a tuple or None if no more rows are available.
Syntax
row = cursor.fetchone()
You should use this method after cursor.execute().
Fetching a Single Row
import mysql.connector # Establish connection to MySQL server connection = mysql.connector.connect( host="localhost", user="root", password="password", database="mydatabase" ) cursor = connection.cursor() # Execute a SELECT query cursor.execute("SELECT * FROM users") # Fetch the first row row = cursor.fetchone() # Print the row print(row) connection.close()
In this example, you may use “SELECT * FROM users
” to get many rows, however, cursor.fetchone()
will returns the first row.
Fetching Several Rows
cursor = connection.cursor() # Execute a SELECT query cursor.execute("SELECT * FROM users") # Fetch and print all rows row = cursor.fetchone() while row is not None: print(row) row = cursor.fetchone() connection.close()
In this example, you can fetch all rows in a while loop.