HOME HTML EDITOR C JAVA PHP python

Python MySQL

Python can connect to a MySQL database server to store, query, update, and delete structured application data. A popular driver is mysql-connector-python, installed via pip install mysql-connector-python.

1. Connecting to MySQL & Creating a Table

Establish a connection with mysql.connector.connect(), use a cursor to run SQL commands, and call commit() for changes:

import mysql.connector

conn = mysql.connector.connect(
    host="localhost",
    user="root",
    password="your_password",
    database="expertsjava_db"
)

cursor = conn.cursor()
cursor.execute("""
    CREATE TABLE IF NOT EXISTS courses (
        id INT AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(100) NOT NULL,
        price INT NOT NULL
    )
""")
conn.commit()

2. Parameterized INSERT & SELECT

Always pass query values as a tuple using %s placeholders to prevent SQL injection, then fetch rows with fetchall():

# Insert a record safely
cursor.execute(
    "INSERT INTO courses (title, price) VALUES (%s, %s)",
    ("Python Full Stack", 1999)
)
conn.commit()

# Query records
cursor.execute("SELECT id, title, price FROM courses")
for row in cursor.fetchall():
    print(row)

3. Updating & Deleting Records

Use WHERE conditions with parameterized values when updating or removing rows, and close the cursor and connection when done:

cursor.execute(
    "UPDATE courses SET price = %s WHERE title = %s",
    (1499, "Python Full Stack")
)
cursor.execute(
    "DELETE FROM courses WHERE id = %s",
    (99,)
)
conn.commit()

cursor.close()
conn.close()
Tip: Never concatenate user input directly into SQL strings with f-strings — always use parameterized queries (%s) and store database credentials in environment variables.