To connect Python with MySQL, you need to install the MySQL Connector/Python library. This library provides a Python interface to MySQL databases. Once you have installed the library, you can connect to a MySQL database using the following code:
Code snippet
import mysql.connector
# Create a connection object
conn = mysql.connector.connect(
host='localhost',
user='root',
password='password',
database='my_database'
)
# Create a cursor object
cursor = conn.cursor()
# Execute a SQL query
cursor.execute('SELECT * FROM my_table')
# Fetch the results
results = cursor.fetchall()
# Print the results
for row in results:
print(row)
# Close the connection
conn.close()
This code will connect to a MySQL database called my_database
on the local host. It will then execute a SQL query to select all rows from the my_table
table. The results of the query will be printed to the console. Finally, the connection to the database will be closed.
Here are some additional things to keep in mind when connecting Python with MySQL:
- The
host
parameter specifies the hostname or IP address of the MySQL server. - The
user
parameter specifies the username for the MySQL database. - The
password
parameter specifies the password for the MySQL database. - The
database
parameter specifies the name of the MySQL database to connect to. - The
cursor
object can be used to execute SQL queries and fetch the results. - The
results
variable is a list of tuples, where each tuple represents a row in the database table. - The
conn.close()
method closes the connection to the MySQL database.