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 do I connect to XAMPP MySQL using Python?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How can I install the MySQL-Python (Python 2.x) module?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I connect Python to a MySQL database?
- How do I use Python to update multiple columns in a MySQL database?
- How do I use Python to query MySQL with multiple conditions?
- How do I use Python to authenticate MySQL on Windows?
- How do I use a Python MySQL refresh cursor?
- How do I use a cursor to interact with a MySQL database in Python?
See more codes...