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