Importing Rows into PostgreSQL from STDIN Using Go
In Go, you can import rows into PostgreSQL from standard input (STDIN) using the pq package. This approach directly feeds the data into the database without the need for intermediate files.
To achieve direct row importing from STDIN, follow these steps:
Example Code:
Here's a code example that demonstrates row importing from STDIN using Go:
<code class="go">package main import ( "database/sql" "fmt" "io" "log" "github.com/lib/pq" ) func main() { db, err := sql.Open("postgres", "host=localhost port=5432 user=postgres password=mysecret dbname=mydatabase") if err != nil { log.Fatal(err) } defer db.Close() rows := [][]string{ {"Rob", "Pike"}, {"Ken", "Thompson"}, {"Robert", "Griesemer"}, } txn, err := db.Begin() if err != nil { log.Fatal(err) } stmt, err := txn.Prepare(pq.CopyIn("test", "first_name", "last_name")) if err != nil { log.Fatal(err) } for _, r := range rows { if _, err = stmt.Exec(r[0], r[1]); err != nil { log.Fatal(err) } } if _, err = stmt.Exec(); err != nil { log.Fatal(err) } if err = stmt.Close(); err != nil { log.Fatal(err) } if err = txn.Commit(); err != nil { log.Fatal(err) } fmt.Println("Rows imported successfully.") }</code>
By following these steps and utilizing the pq package, you can efficiently import data into PostgreSQL directly from STDIN in your Go programs.
The above is the detailed content of How to Import Rows into PostgreSQL from STDIN Using Go?. For more information, please follow other related articles on the PHP Chinese website!