首頁  >  文章  >  後端開發  >  如何使用 Golang 不使用 for 迴圈將 CSV 檔案插入 PostgreSQL 中?

如何使用 Golang 不使用 for 迴圈將 CSV 檔案插入 PostgreSQL 中?

Barbara Streisand
Barbara Streisand原創
2024-10-26 06:54:30616瀏覽

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

使用Golang Sans For 迴圈將CSV 批次插入PostgreSQL

如果您是Golang 新手,希望將CSV 資料插入PostgreSQL 表而不使用查詢 迴圈或原始SQL SQL ,pgx 是您的解決方案。操作方法如下:

  1. 匯入 pg​​x:先匯入 pg​​x,PostgreSQL 的資料庫介面。
<code class="go">import (
    "context"
    "fmt"
    "os"

    "github.com/jackc/pgx/v4"
)</code>
  1. 建立資料庫連線:使用 pgx.Connect() 連接到您的 PostgreSQL 資料庫。
<code class="go">dbconn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL"))
if err != nil {
    panic(err)
}
defer dbconn.Release()</code>
  1. 開啟CSV 檔案:載入您想要的CSV 檔案
<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>
  1. 執行批次插入
:利用CopyFrom() 將CSV 檔案批次插入到名為「csv_test」的表中。
<code class="go">fmt.Print(res.RowsAffected())</code>

顯示結果:列印批次插入影響的行數。 就是這樣!使用 pgx,您可以快速且有效率地將大量 CSV 資料插入 PostgreSQL 資料庫中,而無需手動循環或複雜的查詢。

以上是如何使用 Golang 不使用 for 迴圈將 CSV 檔案插入 PostgreSQL 中?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn