python-mysqlHow can I use Python and MySQL row_factory to fetch data from a database?
Using Python and MySQL row_factory is a great way to fetch data from a database. Here is an example of how to do this:
import mysql.connector
# Connect to the database
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="password",
database="mydatabase"
)
# Create a cursor
mycursor = mydb.cursor()
# Set the row_factory to a dictionary
mycursor.row_factory = mysql.connector.DictCursor
# Execute a query
mycursor.execute("SELECT * FROM customers")
# Fetch the results
result = mycursor.fetchall()
# Print the results
print(result)
Output example
[{'id': 1, 'name': 'John', 'address': 'Highway 37'}, {'id': 2, 'name': 'Peter', 'address': 'Lowstreet 27'}, {'id': 3, 'name': 'Amy', 'address': 'Apple st 652'}]
The code above does the following:
- Imports the
mysql.connector
module - Connects to the database
- Creates a cursor
- Sets the row_factory to a dictionary
- Executes a query
- Fetches the results
- Prints the results
For more information on using Python and MySQL row_factory, see the following links:
More of Python Mysql
- How can I use Python to retrieve data from MySQL?
- How can I use Python and MySQL to create a login system?
- How can I connect Python to a MySQL database?
- How can I use Python to interact with a MySQL database using YAML?
- How can I host a MySQL database using Python?
- How do I fix a bad MySQL handshake error in Python?
- How can I connect Python to a MySQL database using an Xserver?
- How do I connect Python with MySQL using XAMPP?
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python and MySQL?
See more codes...