In Go, you can import rows to PostgreSQL from STDIN using the pq package. Here's a step-by-step solution:
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)
}
txn, err := db.Begin()
if err != nil {
log.Fatalf("begin: %v", err)
}
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)
}
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)
}
}
_, err = stmt.Exec()
if err != nil {
log.Fatalf("exec: %v", err)
}
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.
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