python-mysqlHow can I print the result of a MySQL query in Python?
To print the result of a MySQL query in Python, you can use the fetchall()
method of the cursor
object. This method returns a list of tuples containing the results of the query. The example code below shows how to use fetchall()
to print the result of a SELECT query:
import mysql.connector
# Connect to MySQL
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="passwd",
database="mydatabase"
)
# Create cursor
mycursor = mydb.cursor()
# Execute query
mycursor.execute("SELECT * FROM customers")
# Fetch and print result
result = mycursor.fetchall()
print(result)
Output example
[(1, 'John', 'Highway 21'), (2, 'Peter', 'Lowstreet 4'), (3, 'Amy', 'Apple st 652')]
The code above consists of the following parts:
- Import the
mysql.connector
module. - Connect to the MySQL database.
- Create a cursor object.
- Execute the query.
- Use the
fetchall()
method to fetch the result. - Print the result.
Helpful links
More of Python Mysql
- How do I use Python to query MySQL with multiple conditions?
- How can I use Python and MySQL to create a login system?
- How can I use Python to interact with a MySQL database using YAML?
- How do I use Python to authenticate MySQL on Windows?
- How can I connect Python to a MySQL database using an Xserver?
- How can I use the "order by" statement in Python to sort data in a MySQL database?
- How can I connect to MySQL using Python?
- How can I connect Python to a MySQL database?
- How do I connect to a MySQL database using Python and MySQL Workbench?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
See more codes...