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:
<code class="go">import ( "context" "fmt" "os" "github.com/jackc/pgx/v4" )</code>
<code class="go">dbconn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL")) if err != nil { panic(err) } defer dbconn.Release()</code>
<code class="go">f, err := os.Open(filename) if err != nil { panic(err) } defer func() { _ = f.Close() }()</code>
<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>
<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!