Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • šŸ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • šŸ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • šŸ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • šŸ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • šŸ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • šŸ“ For Each Assignments
    • šŸ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • šŸ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • šŸ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • šŸ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • šŸ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • šŸ“ Assignments
  • Exception
    • Error vs Exception
    • Types of Exception
    • Exception Handling
    • User Defined Exception
    • Logging Exception
    • šŸ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • šŸ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • šŸ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • šŸ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • šŸ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • šŸ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • šŸ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • šŸ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • šŸ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • šŸ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • šŸ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • šŸ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • šŸ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • šŸ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

āœļø Python: Insert Data in MySQL

Sankalan Data Tech Team Verified
Python & MySQL Experts
Making database programming simple and fun for everyone. Learn by doing with real examples!
Read Time: 10 minutes Level: Beginner Topic: MySQL INSERT, Python Prerequisite: Create Table
What's Inside?
  • šŸ“– What is INSERT?
  • šŸ”§ INSERT Syntax
  • āœļø Insert Single Row
  • šŸ“‹ Insert Multiple Rows
  • šŸ’¾ COMMIT Explained
  • šŸ”’ Parameterized Queries
  • šŸ”¢ Getting Last Insert ID
  • āš ļø Error Handling
  • šŸ’¼ Real-World Example
  • āœ… Best Practices
  • šŸŽ® Try It Yourself
  • 🧠 Quick Quiz
  • ā“ FAQ
šŸ“¤ Share this:
Twitter LinkedIn Facebook WhatsApp Copy Link

šŸ“– 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.

šŸ Python Code āž”ļø šŸ“Š MySQL 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!

INSERT INTO table_name (column1, column2, column3) VALUES (value1, value2, value3);

Let me break this down piece by piece:

INSERT INTO – "Hey MySQL, I want to add new data"
table_name – "Which table should I add it to?"
(column1, column2, ...) – "Here are the columns I want to fill"
VALUES (value1, value2, ...) – "And here are the values for those columns"

Here's a real example:

INSERT INTO students (first_name, last_name, age, email) VALUES ('Rahul', 'Sharma', 22, 'rahul@email.com');

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

Method 1: Specify columns (Recommended)
INSERT INTO students (first_name, last_name, age) 
VALUES ('Priya', 'Patel', 25);

āœ… Best practice: Always specify column names. It's clearer and more maintainable.

Method 2: Insert into all columns
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.

Method 3: Insert multiple rows (Efficient)
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:

CREATE TABLE IF NOT EXISTS students ( student_id INT AUTO_INCREMENT PRIMARY KEY, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, age INT, email VARCHAR(100) UNIQUE, joined_date DATE );

Now, let's insert a student:

1 Connect to the database
import mysql.connector

connection = mysql.connector.connect(
    host="localhost",
    user="root",
    password="secret",
    database="myapp_db"
)
cursor = connection.cursor()
2 Write the INSERT query
insert_query = """
INSERT INTO students (first_name, last_name, age, email, joined_date)
VALUES ('Rahul', 'Sharma', 22, 'rahul@email.com', '2024-01-15')
"""
3 Execute and commit
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:

insert_multiple_query = """ INSERT INTO students (first_name, last_name, age, email, joined_date) VALUES ('Priya', 'Patel', 25, 'priya@email.com', '2024-01-15'), ('Amit', 'Singh', 24, 'amit@email.com', '2024-01-16'), ('Sneha', 'Reddy', 23, 'sneha@email.com', '2024-01-16'), ('Vikram', 'Kumar', 26, 'vikram@email.com', '2024-01-17'), ('Anjali', 'Nair', 21, 'anjali@email.com', '2024-01-17') """ cursor.execute(insert_multiple_query) connection.commit() print("āœ… 5 students added successfully!")

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:

# List of students as dictionaries students = [ {"first_name": "Raj", "last_name": "Kumar", "age": 22, "email": "raj@email.com", "joined_date": "2024-01-18"}, {"first_name": "Meera", "last_name": "Iyer", "age": 23, "email": "meera@email.com", "joined_date": "2024-01-18"}, # ... more students ] # Build the query dynamically values_list = [] for s in students: values_list.append(f"('{s['first_name']}', '{s['last_name']}', {s['age']}, '{s['email']}', '{s['joined_date']}')") query = f""" INSERT INTO students (first_name, last_name, age, email, joined_date) VALUES {', '.join(values_list)} """ cursor.execute(query) connection.commit() print(f"āœ… {len(students)} students added!")

āš ļø 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

āŒ Without COMMIT
  • Changes exist only in memory
  • Other users can't see them
  • If your program crashes, changes are lost
āœ… With COMMIT
  • Changes are saved to disk
  • Other users can see them
  • Changes are permanent (even after crash)
# Always commit your changes! cursor.execute("INSERT INTO students ...") connection.commit() # Without this, nothing is saved! # If something goes wrong, rollback try: cursor.execute("INSERT INTO students ...") connection.commit() except Exception as e: connection.rollback() # Undo the changes print("Error, changes rolled back")

šŸ’” 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.

āŒ UNSAFE (Don't do this!)
name = "Robert"
# This is vulnerable to SQL injection!
cursor.execute(f"INSERT INTO students (first_name) VALUES ('{name}')")
āœ… SAFE (Always do this!)
name = "Robert"
# Safe from SQL injection!
cursor.execute("INSERT INTO students (first_name) VALUES (%s)", (name,))

How parameterized queries work:

1 Placeholders

Use %s as a placeholder in your SQL query.

2 Pass values as a tuple

Pass the actual values as a second argument to execute().

3 MySQL handles escaping

MySQL automatically escapes special characters. It's impossible to inject SQL through these placeholders.

Examples of Parameterized Queries

# Example 1: Insert a single row query = "INSERT INTO students (first_name, last_name, age) VALUES (%s, %s, %s)" values = ("Rahul", "Sharma", 22) cursor.execute(query, values) # Example 2: Insert multiple rows with executemany() query = "INSERT INTO students (first_name, last_name, age) VALUES (%s, %s, %s)" students = [ ("Priya", "Patel", 25), ("Amit", "Singh", 24), ("Sneha", "Reddy", 23) ] cursor.executemany(query, students) # Note: executemany, not execute! connection.commit() print(f"āœ… {len(students)} students inserted")

šŸ”’ 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.

query = "INSERT INTO students (first_name, last_name) VALUES (%s, %s)" values = ("Arjun", "Reddy") cursor.execute(query, values) connection.commit() # Get the ID of the newly inserted row new_id = cursor.lastrowid print(f"āœ… Student added with ID: {new_id}")

šŸ’” 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:

Duplicate Entry

Error: Duplicate entry 'rahul@email.com' for key 'email'
You tried to insert a duplicate value in a UNIQUE column.

Data Type Mismatch

Error: Incorrect integer value: 'abc' for column 'age'
You tried to insert text into a number column.

NOT NULL Violation

Error: Column 'first_name' cannot be null
You tried to insert NULL into a NOT NULL column.

How to handle errors properly:

from mysql.connector import Error def insert_student(first_name, last_name, age, email): try: query = """ INSERT INTO students (first_name, last_name, age, email) VALUES (%s, %s, %s, %s) """ values = (first_name, last_name, age, email) cursor.execute(query, values) connection.commit() print(f"āœ… Student {first_name} {last_name} added!") return cursor.lastrowid except mysql.connector.IntegrityError as e: if "Duplicate entry" in str(e): print("āŒ This email already exists!") else: print("āŒ Integrity error:", e) connection.rollback() return None except mysql.connector.DataError as e: print("āŒ Data type error:", e) connection.rollback() return None except mysql.connector.Error as e: print("āŒ Database error:", e) connection.rollback() return None finally: # Clean up pass # Test it insert_student("Rahul", "Sharma", 22, "rahul@email.com") # Works insert_student("Rahul", "Sharma", 22, "rahul@email.com") # Fails - duplicate email

šŸ›”ļø 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
import mysql.connector from mysql.connector import Error class UserSignup: """Handle user signup with MySQL""" def __init__(self, db_config): self.config = db_config self.connection = None self.cursor = None def connect(self): """Establish connection to MySQL""" try: self.connection = mysql.connector.connect(**self.config) self.cursor = self.connection.cursor() return True except Error as e: print(f"Connection error: {e}") return False def email_exists(self, email): """Check if email already exists in the database""" query = "SELECT COUNT(*) FROM students WHERE email = %s" self.cursor.execute(query, (email,)) count = self.cursor.fetchone()[0] return count > 0 def signup(self, first_name, last_name, age, email): """Register a new user""" # Validate input if not first_name or not last_name: return {"success": False, "message": "Name is required"} if not email or "@" not in email: return {"success": False, "message": "Valid email is required"} try: # Check if email exists if self.email_exists(email): return {"success": False, "message": "Email already registered"} # Insert the user query = """ INSERT INTO students (first_name, last_name, age, email, joined_date) VALUES (%s, %s, %s, %s, CURDATE()) """ values = (first_name, last_name, age, email) self.cursor.execute(query, values) self.connection.commit() new_id = self.cursor.lastrowid # Send welcome email (simulated) self.send_welcome_email(email, first_name) return { "success": True, "message": "Welcome!", "user_id": new_id } except Error as e: self.connection.rollback() return {"success": False, "message": f"Signup failed: {e}"} def send_welcome_email(self, email, name): """Simulate sending a welcome email""" print(f"šŸ“§ Welcome email sent to {email} for {name}") def close(self): """Clean up connections""" if self.cursor: self.cursor.close() if self.connection: self.connection.close() # ============================================================ # DEMONSTRATION # ============================================================ if __name__ == "__main__": # Configuration db_config = { "host": "localhost", "user": "root", "password": "secret", "database": "myapp_db" } # Create signup handler signup = UserSignup(db_config) if not signup.connect(): exit() # Test signup print("\nšŸ“ Testing User Signup:") print("-" * 40) # Valid signup result = signup.signup("Priya", "Patel", 25, "priya@email.com") print(f"Result: {result}") # Duplicate email result = signup.signup("Rahul", "Sharma", 22, "priya@email.com") print(f"Result: {result}") # Invalid email result = signup.signup("Amit", "Singh", 24, "invalid") print(f"Result: {result}") signup.close()

šŸŽÆ 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

1 Always use parameterized queries

NEVER use f-strings or string concatenation for SQL. ALWAYS use %s placeholders. This is non-negotiable for security.

2 Always commit your changes

Use connection.commit() after every INSERT, UPDATE, or DELETE. Without it, your changes aren't saved.

3 Use executemany for multiple rows

For inserting many rows, use cursor.executemany(). It's much faster than inserting one by one.

4 Handle errors properly

Use try/except to catch errors. Use rollback() when errors occur to keep data consistent.

5 Validate data before inserting

Check email formats, required fields, and data types before sending to the database. It's better to catch errors early.

6 Use lastrowid when you need the new ID

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!

Loading... 0%
Python Code
============================================= INSERT DATA - PRACTICE ============================================= šŸ“ Inserting students... ---------------------------------------- āœ… Added: Rahul Sharma (ID: 1) āœ… Added: Priya Patel (ID: 2) šŸ“ Inserting 3 more students... āœ… Added: Amit Singh (ID: 3) āœ… Added: Sneha Reddy (ID: 4) āœ… Added: Vikram Kumar (ID: 5) šŸ”„ Trying to insert duplicate email... āŒ Email 'rahul@email.com' already exists! šŸ“‹ All Students: -------------------------------------------------- ID: 1 | Rahul Sharma | Age: 22 | rahul@email.com ID: 2 | Priya Patel | Age: 25 | priya@email.com ID: 3 | Amit Singh | Age: 24 | amit@email.com ID: 4 | Sneha Reddy | Age: 23 | sneha@email.com ID: 5 | Vikram Kumar | Age: 26 | vikram@email.com -------------------------------------------------- Total: 5 students āœ… Done! Inserting data is fun!
šŸ†

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!

1ļøāƒ£ What SQL command adds new data to a table?
2ļøāƒ£ What does connection.commit() do?
3ļøāƒ£ Why should you use parameterized queries?
4ļøāƒ£ How do you get the ID of the newly inserted row?
5ļøāƒ£ Which method is fastest for inserting many rows?

ā“ Frequently Asked Questions

šŸ¤” Why do I need to commit after INSERT? ā–¼

MySQL uses transactions by default. Your changes are stored temporarily until you commit them.

Why? It lets you:

  • Group multiple changes together
  • Undo (rollback) if something goes wrong
  • Keep the database in a consistent state
Without commit(), your data disappears when the connection closes!

šŸ¤” What's the difference between execute() and executemany()? ā–¼

execute() – Runs a single query with one set of values.

executemany() – Runs the same query multiple times with different values. It's much faster for inserting many rows because it reduces network overhead.

Example: Inserting 1000 rows with executemany() takes about 0.5 seconds. Doing it with execute() in a loop takes about 5 seconds.

šŸ¤” What happens if I insert a duplicate email? ā–¼

If you have a UNIQUE constraint on the email column (which you should!), MySQL will raise an IntegrityError with the message "Duplicate entry."

How to handle it:

  • Catch the IntegrityError exception
  • Check if the error is about duplicate email
  • Show a friendly message to the user: "This email is already registered"
  • Use rollback() to undo the failed insert

šŸ¤” Can I insert data without specifying all columns? ā–¼

Yes! You only need to specify the columns you want to fill. MySQL will use:

  • DEFAULT values (if defined)
  • NULL (if the column allows it)
  • AUTO_INCREMENT values (automatically generated)
Example: INSERT INTO students (first_name, last_name) VALUES ('Rahul', 'Sharma');
This will insert a student with only first and last name. All other columns will get their default values.

šŸ¤” What's the maximum number of rows I can insert at once? ā–¼

The limit is set by the max_allowed_packet setting in MySQL (default is 4MB-16MB).

Practical advice:

  • Insert in batches of 100-1000 rows
  • Don't try to insert 100,000 rows in one query
  • If you have many rows, batch them and commit every 1000 rows
Example: executemany() can handle large batches, but it's better to split into smaller batches for memory and performance reasons.

ā¬…ļø Previous: Create Table Next: Insert Multiple Rows →