python-mysqlHow do I use the Python MySQL fetchone command?
The Python MySQL fetchone command allows you to retrieve a single row from a MySQL table query result. It is used to fetch the next row of a query result set and return a single tuple, or None if no more rows are available.
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="passwd",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchone()
print(myresult)
Output example
('John', 'Highway 21')
The code above establishes a connection to a MySQL database, creates a cursor object, executes a SQL query to select all records from the customers table, and then uses the fetchone() method to retrieve a single row from the result set.
Code explanation
import mysql.connector
: imports the MySQL Connector Python module.mydb = mysql.connector.connect(host="localhost", user="user", passwd="passwd", database="mydatabase")
: establishes a connection to a MySQL database.mycursor = mydb.cursor()
: creates a cursor object.mycursor.execute("SELECT * FROM customers")
: executes a SQL query to select all records from the customers table.myresult = mycursor.fetchone()
: uses the fetchone() method to retrieve a single row from the result set.print(myresult)
: prints the record retrieved from the result set.
Helpful links
More of Python Mysql
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python to a MySQL database?
- How can I connect Python to a MySQL database using an Xserver?
- How can I connect Python and MySQL?
- How can I retrieve unread results from a MySQL database using Python?
- How can I use Yum to install the MySQLdb Python module?
- How to compile a MySQL-Python application for x86_64-Linux-GNU-GCC?
- How can I use Python to interact with a MySQL database?
- How do I use Python to authenticate MySQL on Windows?
- How can I use the WHERE IN clause in Python to query a MySQL database?
See more codes...