python-mysqlHow can I use Python to fetch data from a MySQL database?
Python can be used to fetch data from a MySQL database using the MySQLdb
module. The following example code block shows how to connect to a database, create a cursor, execute a query, and print the results:
# Import the MySQLdb module
import MySQLdb
# Connect to the database
db = MySQLdb.connect(host="localhost", user="your_username", passwd="your_password", db="your_database")
# Create a cursor
cursor = db.cursor()
# Execute a query
cursor.execute("SELECT * FROM your_table")
# Print the results
for row in cursor.fetchall():
print(row)
Code explanation
-
import MySQLdb
: This imports theMySQLdb
module, which provides the functions needed to connect to and query a MySQL database. -
db = MySQLdb.connect(host="localhost", user="your_username", passwd="your_password", db="your_database")
: This establishes a connection to the database. Thehost
,user
,passwd
, anddb
parameters are used to specify the hostname, username, password, and database name, respectively. -
cursor = db.cursor()
: This creates a cursor object, which is used to execute queries and fetch results. -
cursor.execute("SELECT * FROM your_table")
: This executes a query to select all records from the specified table. -
for row in cursor.fetchall():
: This loop iterates over the results of the query and prints each row.
For more information about using Python to connect to and query a MySQL database, see the following links:
More of Python Mysql
- 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 Python to update multiple columns in a MySQL database?
- How do I use Python to show the MySQL processlist?
- How can I connect Python to a MySQL database?
- How can I use Python to interact with a MySQL database using YAML?
- How do Python and MySQL compare to MariaDB?
- How can I convert a MySQL query result to a Python dictionary?
- How do I connect to a MySQL database using XAMPP and Python?
- How can I use Python to perform an upsert on a MySQL database?
See more codes...