Prisma insert multiple rows

To insert multiple rows into a Prisma database, you can use the Prisma client’s createMany method. This method allows you to insert multiple rows at once, which can be more efficient than inserting them one by one.

Example:

    
const { PrismaClient } = require('@prisma/client');

const prisma = new PrismaClient();

async function insertMultipleRows() {
  try {
    const rowsToInsert = [
      {
        name: 'Row 1',
        value: 10,
      },
      {
        name: 'Row 2',
        value: 20,
      },
      {
        name: 'Row 3',
        value: 30,
      },
    ];

    const insertedRows = await prisma.tableName.createMany({
      data: rowsToInsert,
    });

    console.log('Inserted rows:', insertedRows);
  } catch (error) {
    console.error('Error inserting rows:', error);
  } finally {
    await prisma.$disconnect();
  }
}

insertMultipleRows();
    
  

In the example above, we assume you have a table named tableName in your Prisma schema. The rowsToInsert array contains objects representing the data to be inserted into the table. Each object represents a row and contains property-value pairs for the column values.

The createMany method is called with the data parameter set to the rowsToInsert array. It returns the inserted rows as an array.

Make sure to replace tableName with the actual name of your table in the Prisma schema.

Leave a comment