SwadhyAI Notes

All Python notes

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")
)