Home  >  Article  >  Backend Development  >  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?

Linda Hamilton
Linda HamiltonOriginal
2024-10-24 18:34:31887browse

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

<code class="go">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)
}</code>

Step 2: Start a Transaction

<code class="go">txn, err := db.Begin()
if err != nil {
    log.Fatalf("begin: %v", err)
}</code>

Step 3: Prepare the Copy Statement

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

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

Step 4: Execute the Copy Statement

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

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

Step 5: Execute Final Copy Statement

<code class="go">_, err = stmt.Exec()
if err != nil {
    log.Fatalf("exec: %v", err)
}</code>

Step 6: Close the Statement and Commit the Transaction

<code class="go">stmt.Close()
err = txn.Commit()
if err != nil {
    log.Fatalf("commit: %v", err)
}</code>

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

The above is the detailed content of How to Import Data from STDIN to PostgreSQL Using Go\'s pq Package?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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