Home  >  Article  >  Backend Development  >  How do I insert a CSV file into PostgreSQL using Golang without for loops?

How do I insert a CSV file into PostgreSQL using Golang without for loops?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 06:54:30616browse

How do I insert a CSV file into PostgreSQL using Golang without for loops?

Bulk Insert CSV into PostgreSQL Using Golang Sans For Loops

If you're a Golang newbie looking to insert CSV data into a PostgreSQL table without resorting to for loops or raw SQL queries, pgx is your solution. Here's how:

  1. Import pgx: Begin by importing pgx, a database interface for PostgreSQL.
<code class="go">import (
    "context"
    "fmt"
    "os"

    "github.com/jackc/pgx/v4"
)</code>
  1. Establish Database Connection: Connect to your PostgreSQL database using pgx.Connect().
<code class="go">dbconn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL"))
if err != nil {
    panic(err)
}
defer dbconn.Release()</code>
  1. Open CSV File: Load the CSV file you wish to import.
<code class="go">f, err := os.Open(filename)
if err != nil {
    panic(err)
}
defer func() { _ = f.Close() }()</code>
  1. Perform Bulk Insert: Utilize CopyFrom() to perform a bulk insert from the CSV file into a table named "csv_test".
<code class="go">res, err := dbconn.Conn().PgConn().CopyFrom(context.Background(), f, "COPY csv_test FROM STDIN (FORMAT csv)")
if err != nil {
    panic(err)
}</code>
  1. Display Result: Print the number of rows affected by the bulk insert.
<code class="go">fmt.Print(res.RowsAffected())</code>

That's it! Using pgx, you can swiftly and efficiently insert large amounts of CSV data into your PostgreSQL database without the need for manual loops or complex queries.

The above is the detailed content of How do I insert a CSV file into PostgreSQL using Golang without for 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