To connect to a MySQL database with Python, you can use the “MySQL-connector Python” library.
This is a detailed tutorial on how to use it:
1. Install the MySQL Connector:
First, install the MySQL connector package:
pip install mysql-connector-python
2. Import and Connect to the Database:
Using the mysql.connector module, you can use Python to establish a connection to a MySQL database through installation.
3. Here is the code for connecting to MySQL:
import mysql.connector
# Create a connection object
connection = mysql.connector.connect(
host="localhost", # Your database server address (e.g., 'localhost')
user="yourusername", # Your MySQL username
password="yourpassword", # Your MySQL password
database="yourdatabase" # Database name
)
# Check if connection is successful
if connection.is_connected():
print("Connected to the MySQL database")
# Close the connection when done
connection.close()