š What is INSERT in MySQL?
Imagine you've built a beautiful house. You've set up the rooms (that's your database), you've placed the furniture (that's your tables), and now it's time to move people in.
In the database world, INSERT is exactly that ā it's how you add data to your tables. It's the command that says, "Hey MySQL, here's some information, please store it for me."
š Think of it like filling out a form.
You know when you fill out a form online? You enter your name, email, address, and click "Submit." The website then inserts that data into their database.
That's exactly what INSERT does! It takes the data you provide and adds it as a new row in your table.
(Your data travels from Python to the database)
Why is INSERT so important?
- It's how your application stores user data ā signups, orders, posts, comments
- It's how data gets into your database ā without INSERT, your tables would always be empty
- It's the foundation of CRUD ā Create (INSERT), Read (SELECT), Update (UPDATE), Delete (DELETE)
š” Fun fact: In a typical web application, INSERT operations happen all the time. Every time someone signs up, posts a comment, or places an order ā that's an INSERT!
š§ INSERT Syntax Explained
Before we write any Python code, let's understand the SQL syntax for INSERT. It's actually quite simple!
Let me break this down piece by piece:
Here's a real example:
This adds a new student named Rahul Sharma, age 22, with email rahul@email.com.
š” Important: The order of columns and values must match! The first value goes into the first column, second value into the second column, and so on.
Three Ways to Write INSERT
INSERT INTO students (first_name, last_name, age) VALUES ('Priya', 'Patel', 25);
ā Best practice: Always specify column names. It's clearer and more maintainable.
INSERT INTO students VALUES (NULL, 'Amit', 'Singh', 24, 'amit@email.com', '2024-01-15');
ā ļø You must provide values for ALL columns in order. NULL is used for AUTO_INCREMENT columns.
INSERT INTO students (first_name, last_name, age) VALUES ('Sneha', 'Reddy', 23), ('Vikram', 'Kumar', 26), ('Anjali', 'Nair', 21);
š Efficient: Insert multiple rows in a single query. Much faster than inserting one by one!
š Remember: When you use AUTO_INCREMENT columns (like student_id), you don't need to provide a value. MySQL will generate it automatically. Just use NULL or skip the column entirely.
āļø Insert a Single Row
Let's start with the simplest case: adding one student to our table.
Before we begin: Make sure you have the students table from the previous tutorial. If not, here's a quick reminder of what it looks like:
Now, let's insert a student:
import mysql.connector connection = mysql.connector.connect( host="localhost", user="root", password="secret", database="myapp_db" ) cursor = connection.cursor()
insert_query = """ INSERT INTO students (first_name, last_name, age, email, joined_date) VALUES ('Rahul', 'Sharma', 22, 'rahul@email.com', '2024-01-15') """
cursor.execute(insert_query) connection.commit() # Save changes to the database print("ā Student added successfully!") # Clean up cursor.close() connection.close()
š That's it! You just inserted your first record into the database. Notice that we didn't specify student_id ā MySQL handled it automatically!
š” Pro tip: Always use connection.commit() after INSERT, UPDATE, or DELETE. Without it, your changes won't be saved to the database. This is called a transaction, and we'll learn more about it later.
š Insert Multiple Rows
What if you have a list of students to add? You could insert them one by one, but that's slow. The better way is to insert all of them in one query.
š Think of it like a carpool vs driving alone.
If you have 5 people going to the same place, it's faster to put them all in one car than to take 5 separate cars.
Same with INSERT! Inserting multiple rows in one query is much faster than inserting them one by one.
Here's how to insert multiple students:
Notice the structure:
- Each row is inside parentheses
() - Rows are separated by commas
, - The last row doesn't have a comma after it
ā” Performance tip: Inserting 100 rows in one query is about 5-10 times faster than inserting them individually. Always batch your inserts when possible!
Inserting Multiple Rows from Python Lists
In real applications, you often have data in Python lists or dictionaries. Here's how to insert them efficiently:
ā ļø Security warning: The above example uses f-strings to build the query. This is NOT SAFE for production because it's vulnerable to SQL injection. We'll learn the proper (safe) way in the next section using parameterized queries.
š¾ COMMIT ā Saving Your Changes
This is something that confuses many beginners. Let me explain it with a simple analogy.
š Think of it like writing an exam.
You write all your answers on the paper. But the paper isn't officially submitted until you hand it over to the invigilator.
In MySQL:
INSERT, UPDATE, DELETE
= writing your answers
COMMIT
= submitting your paper
- Changes exist only in memory
- Other users can't see them
- If your program crashes, changes are lost
- Changes are saved to disk
- Other users can see them
- Changes are permanent (even after crash)
š” Remember:
connection.commit() is like hitting "Save" in a document. Without it, all your hard work disappears when you close the connection!
š Parameterized Queries ā The Right Way
This is extremely important for security. Let me explain why.
šØ SQL Injection Alert!
Imagine this: Someone enters "Robert'; DROP TABLE students; --" as their name...
If you build queries with f-strings, that could delete your entire table!
Parameterized queries protect you from this. They separate the SQL code from the data.
name = "Robert" # This is vulnerable to SQL injection! cursor.execute(f"INSERT INTO students (first_name) VALUES ('{name}')")
name = "Robert" # Safe from SQL injection! cursor.execute("INSERT INTO students (first_name) VALUES (%s)", (name,))
How parameterized queries work:
Use %s as a placeholder in your SQL query.
Pass the actual values as a second argument to execute().
MySQL automatically escapes special characters. It's impossible to inject SQL through these placeholders.
Examples of Parameterized Queries
š Golden rule: NEVER use f-strings or string concatenation to build SQL queries with user input. ALWAYS use parameterized queries. It's not optional ā it's a security necessity!
š¢ Getting the Last Insert ID
Often, after inserting a new record, you need to know what ID was assigned. For example, after a user signs up, you might want to use their new user ID for something else.
MySQL gives you a simple way to get this: lastrowid.
š” When to use lastrowid:
- After a user signs up ā use their new ID to create a profile
- After a customer places an order ā use the order ID to show a confirmation
- After a product is added ā use the product ID to upload images
ā ļø Error Handling
Things can go wrong when inserting data. Here are the most common errors and how to handle them:
Error: Duplicate entry 'rahul@email.com' for key 'email'
You tried to insert a duplicate value in a UNIQUE column.
Error: Incorrect integer value: 'abc' for column 'age'
You tried to insert text into a number column.
Error: Column 'first_name' cannot be null
You tried to insert NULL into a NOT NULL column.
How to handle errors properly:
š”ļø Always use rollback(): When an error occurs, use connection.rollback() to undo any partial changes. This prevents your database from being left in an inconsistent state.
š¼ Real-World Example: User Signup
Let's build something practical ā a user signup system. This is a common real-world scenario:
- A user fills out a signup form
- We validate their input
- We insert their data into the database
- We check if the email already exists
- We send a welcome message
šÆ What we built: A complete user signup system with:
- Input validation
- Duplicate email checking
- Secure parameterized queries
- Error handling
- Welcome email simulation
- Proper cleanup
ā Best Practices for INSERT
NEVER use f-strings or string concatenation for SQL. ALWAYS use %s placeholders. This is non-negotiable for security.
Use connection.commit() after every INSERT, UPDATE, or DELETE. Without it, your changes aren't saved.
For inserting many rows, use cursor.executemany(). It's much faster than inserting one by one.
Use try/except to catch errors. Use rollback() when errors occur to keep data consistent.
Check email formats, required fields, and data types before sending to the database. It's better to catch errors early.
After inserting, use cursor.lastrowid to get the auto-generated ID of the new record.
š Summary: The most important rule is security. Always use parameterized queries. The second most important rule is reliability. Always use commit, rollback, and error handling.
š® Try It Yourself
Play with the code below. Click "Run" to insert students into our simulated database!
You're Crushing It!
You now know how to insert data into MySQL from Python. You understand parameterized queries, error handling, and real-world use cases.
š§ Quick Quiz
Test your INSERT knowledge!
connection.commit() do?