Google News
logo
Python Program to Use the fetchone() method to fetch only one row in a table
Here's a Python program to use the `fetchone()` method to fetch only one row in a table :
Program :
import mysql.connector

# Establish a connection to the database
db = mysql.connector.connect(
    host="localhost",
    user="yourusername",
    password="yourpassword",
    database="yourdatabase"
)

# Create a cursor object to execute queries
cursor = db.cursor()

# Execute the query to select only one row from a table
cursor.execute("SELECT * FROM tablename WHERE column1='value'")

# Fetch one row returned by the query
row = cursor.fetchone()

# Display the row
print(row)

# Close the database connection
db.close()
In the above program, we first establish a connection to the MySQL database using the `mysql.connector` module. We then create a cursor object to execute queries.

The `SELECT` statement is used to select only one row from a table. In this example, we are selecting all columns from a table called `tablename` where `column1` has a value of `'value'`. You can replace these column names and table name with your own.

The `fetchone()` method is used to fetch only one row returned by the query. We then display the row using the `print()` function.

Finally, we close the database connection using the `close()` method.