In this example we will show how to fetch only one row from a table and display the result in Python MySQL.
Source Code
import mysql.connector
# connect to server
mydb = mysql.connector.connect(
host="localhost",
port=3306,
user="yourusername",
password="yourpassword",
db="mydatabase"
)
# get a cursor
mycursor = mydb.cursor()
# execute a query
mycursor.execute("SELECT * FROM us_state")
# get the first row of the result
result = mycursor.fetchone()
print(result)
# close the connection
mydb.close()
Output:
(0, 'Alabama', 'AL', 'Montgomery', 52420)