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 can I use Python to retrieve data from MySQL?
- How do I use an online compiler to write Python code for a MySQL database?
- How can I use the MySQL Connector in Python?
- How can I connect to MySQL using Python?
- How do I access MySQL using Python?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I retrieve the last insert ID in MySQL using Python?
- How do I update values in a MySQL database using Python?
- How can I connect Python and MySQL?
- How can I connect Python to a MySQL database?
See more codes...