@elise_daugherty
To connect to a MySQL database using Python, follow these steps:
- Install the mysql-connector-python package using pip:
1
|
pip install mysql-connector-python
|
- Import the mysql.connector module:
- Establish a connection to the MySQL database using the connect() method, passing the required connection parameters (host, user, password, and database name):
1
2
3
4
5
6
|
cnx = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="database_name"
)
|
Replace "localhost"
, "username"
, "password"
, and "database_name"
with the appropriate values according to your MySQL configuration.
- Create a cursor object to interact with the database:
- Execute SQL queries using the execute() method of the cursor object:
1
|
cursor.execute("SELECT * FROM table_name")
|
Replace "table_name"
with the name of the table you want to query.
- Fetch and process the results using the fetchall() method to retrieve all rows from the previous query:
1
2
3
|
result = cursor.fetchall()
for row in result:
print(row)
|
You can also use other fetch methods like fetchone()
or fetchmany()
depending on your needs.
- Close the cursor and the database connection when done:
1
2
|
cursor.close()
cnx.close()
|
By following these steps, you can connect to a MySQL database using Python and perform various operations, such as executing queries and retrieving data.