logo

Inserting Data

INSERT adds new rows to a table. Always use parameterized queries to prevent SQL injection.

cursor.execute(
    "INSERT INTO users (name, age) VALUES (?, ?)",
    ("Alice", 30)
)
conn.commit()

The ? placeholders are filled with values from the tuple. Never build SQL by concatenating strings - that's a security vulnerability.

Insert multiple rows at once with executemany():

users = [("Alice", 30), ("Bob", 25), ("Charlie", 35)]
cursor.executemany(
    "INSERT INTO users (name, age) VALUES (?, ?)",
    users
)
conn.commit()

The commit() saves changes to the database. Without it, your inserts won't persist.

I cover safe data insertion in my SQL with Python course.