MySQL Getting Started ๐ฌ
Python + MySQL
MySQL is the world's most popular open-source relational database. Python can connect to MySQL using the mysql-connector-python driver.
โจ Install MySQL Driver
Python needs a MySQL driver to access the MySQL database. We recommend MySQL Connector.
Terminal
pip install mysql-connector-python
๐งช Test Installation
Test if the installation was successful:
python
import mysql.connector
# If no error, it's installed!๐ Create Connection
Connect to your MySQL database:
python
import mysql.connector
mydb = mysql.connector.connect(
host="localhost", # or your server IP
user="yourusername",
password="yourpassword"
)
print(mydb) # <mysql.connector.connection.MySQLConnection object...>โ ๏ธ Security Warning
Never hardcode credentials in your code! Use environment variables or configuration files that are not version-controlled.
python
import os
import mysql.connector
mydb = mysql.connector.connect(
host=os.getenv("DB_HOST"),
user=os.getenv("DB_USER"),
password=os.getenv("DB_PASSWORD")
)