What is the fetchone() method? Explain its use in MySQL Python?

Fetchone() method

Fetchone() method is used when you want to select only the first row from the table. This method only returns the first row from the MySQL table.

Use of fetchone() method

The fetchone() is not used as a query to be used to the cursor object. The query passed is “SELECT *” which fetches all the rows from the table.Later , we operate fetchone() method on the result returned by “SELECT *”. The fetchone() method then fetches the first row from that result.

Steps you need to follow to fetch first row from a table using MySQL in python

  • import MySQL connector

  • establish connection with the connector using connect()

  • create the cursor object using cursor() method

  • create a query using “SELECT *” statement

  • execute the SQL query using execute() method

  • operate fetchone() method on the result returned by “SELECT *” query.

  • close the connection

Suppose, we have a table named “MyTable” and we want to get only the first row from it.

|    Name  |  Class  |    City   |    Marks   |
|    Karan |    4    | Amritsar  |    95      |
|    Sahil |    6    | Amritsar  |    93      |
|    Kriti |    3    | Batala    |    88      |
|   Khushi |    9    | Delhi     |    90      |
|    Kirat |    5    | Delhi     |    85      |


import mysql.connector

db=mysql.connector.connect(host="your host", user="your username", password="your password",database="database_name")

query="SELECT * FROM MyTable"

#the cursor object has all the rows returned by the query
#get the first row using the fetchone() method

The above code gets the first row from the table and prints it.


(‘Karan’, 4, ‘Amritsar’ , 95)