"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Import Data from STDIN to PostgreSQL Using Go\'s pq Package?

How to Import Data from STDIN to PostgreSQL Using Go\'s pq Package?

Published on 2024-11-17
Browse:611

How to Import Data from STDIN to PostgreSQL Using Go\'s pq Package?

How do I import rows to Postgresql from STDIN? [duplicate]

In Go, you can import rows to PostgreSQL from STDIN using the pq package. Here's a step-by-step solution:

Step 1: Prepare the Database Connection

import (
    "database/sql"

    "github.com/lib/pq"
)

db, err := sql.Open("postgres", "dbname=mydb user=myuser password=mypassword")
if err != nil {
    log.Fatalf("open: %v", err)
}

Step 2: Start a Transaction

txn, err := db.Begin()
if err != nil {
    log.Fatalf("begin: %v", err)
}

Step 3: Prepare the Copy Statement

Use pq.CopyIn() to create a prepared statement.

stmt, err := txn.Prepare(pq.CopyIn("test_table", "column1", "column2", ...))
if err != nil {
    log.Fatalf("prepare: %v", err)
}

Step 4: Execute the Copy Statement

Iterate through your data and execute stmt.Exec() for each row.

for _, row := range rows {
    _, err = stmt.Exec(row.Column1, row.Column2, ...)
    if err != nil {
        log.Fatalf("exec: %v", err)
    }
}

Step 5: Execute Final Copy Statement

_, err = stmt.Exec()
if err != nil {
    log.Fatalf("exec: %v", err)
}

Step 6: Close the Statement and Commit the Transaction

stmt.Close()
err = txn.Commit()
if err != nil {
    log.Fatalf("commit: %v", err)
}

This code will efficiently import rows from STDIN to your PostgreSQL table.

Release Statement This article is reprinted at: 1729744624 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3