How to insert multiple records?

To insert multiple records into a database using SQL, you can use the INSERT INTO statement with multiple value sets. Here's an example for inserting multiple records into a table named students:

INSERT INTO students (name, age, grade) VALUES
('Alice', 20, 'A'),
('Bob', 21, 'B'),
('Charlie', 22, 'C');

In this example, three records are inserted into the students table with their respective name, age, and grade.

If you're using a programming language like Python with a library such as sqlite3, you can also insert multiple records like this:

import sqlite3

# Connect to the database
conn = sqlite3.connect('example.db')
cursor = conn.cursor()

# Create a list of tuples containing the records to insert
records = [
    ('Alice', 20, 'A'),
    ('Bob', 21, 'B'),
    ('Charlie', 22, 'C')
]

# Insert multiple records using executemany
cursor.executemany('INSERT INTO students (name, age, grade) VALUES (?, ?, ?)', records)

# Commit the changes and close the connection
conn.commit()
conn.close()

This code connects to a SQLite database, prepares a list of records, and uses executemany to insert them into the students table.

0 Comments

no data
Be the first to share your comment!