How to Insert Multiple Rows in MySQL

  1. Using the INSERT Statement
  2. Inserting Multiple Rows with Python
  3. Bulk Insert with CSV Files
  4. Conclusion
  5. FAQ
How to Insert Multiple Rows in MySQL

In today’s post, we’ll learn how to insert multiple rows in MySQL. Whether you’re managing a small database or a large-scale application, knowing how to efficiently insert multiple records can save you a lot of time and resources. MySQL provides several methods to achieve this, allowing you to streamline your data management tasks.

In this article, we’ll explore various techniques to insert multiple rows, including using the INSERT statement and leveraging Python scripts to automate the process. By the end of this guide, you’ll be equipped with the knowledge to handle bulk inserts like a pro. Let’s dive in!

Using the INSERT Statement

The simplest way to insert multiple rows in MySQL is by using the INSERT statement. This method allows you to add several rows in a single query, which is both efficient and straightforward. The syntax for inserting multiple rows looks like this:

INSERT INTO table_name (column1, column2, column3)
VALUES
(value1a, value2a, value3a),
(value1b, value2b, value3b),
(value1c, value2c, value3c);

For example, if you have a table called employees with columns name, position, and salary, your query might look like this:

INSERT INTO employees (name, position, salary)
VALUES
('Alice', 'Developer', 70000),
('Bob', 'Designer', 60000),
('Charlie', 'Manager', 80000);

Output:

Query OK, 3 rows affected

Using this method is efficient because it minimizes the number of round trips between your application and the database server. Instead of executing multiple single-row insert statements, you can perform a single operation that inserts all your data at once. This not only speeds up the process but also reduces the load on your database server. However, be cautious with the number of rows you insert at once, as very large inserts can lead to performance issues or even errors if they exceed the maximum allowed packet size.

Inserting Multiple Rows with Python

If you’re working with a Python application, you can use the MySQL connector library to insert multiple rows seamlessly. This method is particularly useful when you’re dealing with dynamic data or data stored in lists or dictionaries. Below is a basic example of how to do this.

First, make sure you have the MySQL connector installed. You can do this with pip:

pip install mysql-connector-python

Once you have the library, you can use the following code to insert multiple rows:

import mysql.connector

connection = mysql.connector.connect(
    host='localhost',
    user='your_username',
    password='your_password',
    database='your_database'
)

cursor = connection.cursor()

sql = "INSERT INTO employees (name, position, salary) VALUES (%s, %s, %s)"
values = [
    ('Alice', 'Developer', 70000),
    ('Bob', 'Designer', 60000),
    ('Charlie', 'Manager', 80000)
]

cursor.executemany(sql, values)
connection.commit()

print(cursor.rowcount, "rows were inserted.")

cursor.close()
connection.close()

Output:

3 rows were inserted.

In this example, we first establish a connection to the MySQL database using the MySQL connector. Then, we define the SQL command for inserting records, using placeholders (%s) for the values. The values list contains tuples, each representing a row to be inserted. The executemany method is used to execute the SQL statement for all the rows in the list. Finally, we commit the transaction to make the changes permanent and close the cursor and connection.

This method is particularly advantageous for inserting a larger number of records because it allows you to handle data programmatically. You can easily modify the values list based on user input or data retrieved from another source, making it a flexible solution for various applications.

Bulk Insert with CSV Files

Another efficient way to insert multiple rows into a MySQL database is by using CSV files. This method is especially useful when you have a large dataset to import. You can load data from a CSV file directly into your MySQL table using the LOAD DATA INFILE command. Here’s how it works.

First, ensure your CSV file is formatted correctly. For example, if you have a file named employees.csv with the following contents:

name,position,salary
Alice,Developer,70000
Bob,Designer,60000
Charlie,Manager,80000

You can use the following SQL command to load this data into your employees table:

LOAD DATA INFILE '/path/to/employees.csv'
INTO TABLE employees
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;

Output:

Query OK, 3 rows affected

In this command, LOAD DATA INFILE specifies the path to your CSV file. The FIELDS TERMINATED BY clause indicates how the fields in your CSV are separated, while LINES TERMINATED BY specifies the line ending character. The IGNORE 1 ROWS clause is used to skip the header row of the CSV file.

This method is incredibly fast and efficient for bulk inserts. However, be mindful of file permissions and ensure that the MySQL server has access to the specified file path. This method is ideal for data migration tasks or when you need to import large datasets from external sources.

Conclusion

Inserting multiple rows in MySQL is a crucial skill for anyone working with databases. Whether you choose to use the traditional INSERT statement, leverage Python scripts, or import data from CSV files, each method has its advantages. Understanding these techniques not only enhances your efficiency but also improves your overall data management practices. With the knowledge gained from this article, you can confidently handle bulk inserts and streamline your database operations.

FAQ

  1. How many rows can I insert at once in MySQL?
    You can insert a maximum of 65,535 rows in a single INSERT statement, but performance may vary based on your server settings.
  1. What is the difference between INSERT and REPLACE in MySQL?
    INSERT adds new rows, while REPLACE will insert a new row or update an existing one if a duplicate key is found.

  2. Can I use prepared statements for bulk inserts?
    Yes, prepared statements can be used for bulk inserts to enhance security and performance.

  3. What happens if an error occurs during a bulk insert?
    If an error occurs, the entire transaction may be rolled back depending on your transaction settings.

  4. Is it possible to insert data from another table?
    Yes, you can use the INSERT INTO … SELECT statement to copy data from one table to another.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Shraddha Paghdar avatar Shraddha Paghdar avatar

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

LinkedIn

Related Article - MySQL Row