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

Barbara Streisand
Release: 2024-10-26 06:54:30
Original
637 people have browsed it

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>
Copy after login
  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>
Copy after login
  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>
Copy after login
  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>
Copy after login
  1. Display Result: Print the number of rows affected by the bulk insert.
<code class="go">fmt.Print(res.RowsAffected())</code>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!