Posted by Kosal
You can connect to MySQL using Python by utilizing the mysql-connector-python
library, which provides a Python interface to MySQL databases. Here's a step-by-step guide on how to do this:
mysql-connector-python
:First, you need to install the mysql-connector-python
package if you haven't already. You can do this via pip:
pip install mysql-connector-python
Import the mysql.connector
module in your Python script or interactive session.
import mysql.connector
Create a connection to your MySQL database using the connect()
function. You need to provide the necessary connection parameters such as host, user, password, and database name.
# Replace these values with your actual database credentials
config = {
'user': 'your_username',
'password': 'your_password',
'host': 'your_host',
'database': 'your_database_name',
'raise_on_warnings': True
}
try:
conn = mysql.connector.connect(**config)
print("Connected to MySQL database")
except mysql.connector.Error as err:
print(f"Error: {err}")
Once the connection is established successfully, you can execute SQL queries using the cursor
object.
cursor = conn.cursor()
# Example: Execute a query
cursor.execute("SELECT * FROM your_table")
rows = cursor.fetchall()
for row in rows:
print(row)
cursor.close()
After you're done with the database operations, make sure to close the connection.
conn.close()
That's it! This is a basic example of connecting to MySQL using Python. Make sure to replace placeholders like your_host
, your_username
, your_password
, and your_database_name
with your actual database credentials and database name.