Home >Backend Development >Golang >How to Bulk Insert CSV Data into PostgreSQL Using Go, GORM, and the pgx Library Without Loops?

How to Bulk Insert CSV Data into PostgreSQL Using Go, GORM, and the pgx Library Without Loops?

Susan Sarandon
Susan SarandonOriginal
2024-10-27 00:02:30303browse

How to Bulk Insert CSV Data into PostgreSQL Using Go, GORM, and the pgx Library Without Loops?

Inserting CSV Data into PostgreSQL Without For Loops Using Go and GORM

In this scenario, you have a CSV file with data you want to bulk insert into a PostgreSQL table using Go and the GORM ORM, without employing for loops or SQL raw queries.

The pgx library can be utilized for this task, as demonstrated in the following code snippet:

<code class="go">package main

import (
    "context"
    "database/sql"
    "fmt"
    "os"

    "github.com/jackc/pgx/v4/pgxpool"
)

func main() {
    filename := "foo.csv"
    dbconn, err := pgxpool.Connect(context.Background(), os.Getenv("DATABASE_URL"))
    if err != nil {
        panic(err)
    }
    defer dbconn.Close()

    f, err := os.Open(filename)
    if err != nil {
        panic(err)
    }
    defer func() { _ = f.Close() }()

    res, err := dbconn.Conn().PgConn().CopyFrom(context.Background(), f, "COPY csv_test FROM STDIN (FORMAT csv)")
    if err != nil {
        panic(err)
    }

    fmt.Print(res.RowsAffected())
}</code>

In this code:

  1. The pgx/v4 and pgxpool libraries are imported to establish a connection pool to the PostgreSQL database using the DATABASE_URL environment variable.
  2. The CSV file ("foo.csv") is opened for reading.
  3. The CopyFrom method is utilized to copy the CSV data into the csv_test table. The (FORMAT csv) argument specifies the data format.
  4. Finally, the number of rows affected by the copy operation is printed to the console.

The above is the detailed content of How to Bulk Insert CSV Data into PostgreSQL Using Go, GORM, and the pgx Library Without Loops?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn