在阅读github.com/lib/pq
文档后,我仍然不清楚是否可以使用简单的COPY <table> FROM <file> CSV HEADER
命令从CSV文件复制数据。
这就是我想要做的事情:
func CopyFromCSV(con Con, tableName, fileName string) error {
_, err := con.Exec(fmt.Sprintf("TRUNCATE %s", tableName))
if err != nil {
return err
}
stm, err := con.Prepare(fmt.Sprintf("COPY %s FROM '%s' CSV HEADER", tableName, fileName))
if err != nil {
return err
}
defer stm.Close()
_, err = stm.Exec()
return err
}
tableName
是现有表,fileName
是现有csv文件的绝对路径。
我在con.Prepare
电话后始终收到以下错误:pq: unknown response for copy query: 'C'
是否可以使用github.com/lib/pq
驱动程序在Go中使用postgres数据库执行此操作?
答案 0 :(得分:0)
可以在此处找到执行COPY命令的粗略模板-https://play.golang.org/p/6y5v3IW8kD
下面的代码应该对您有用。
func copyTest() {
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=verify-full",host, port, user, password, dbname)
db, err := sql.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
defer db.Close()
err = db.Ping()
if err != nil {
panic(err)
}
tx, err := db.Begin()
if err != nil {
panic(err)
}
_, err = tx.Exec("copy metadata.charvalues_temp from 'C:\\yourlocation\\yourfile.csv' with csv")
if err != nil {
panic(err)
}
err = tx.Commit()
if err != nil {
panic(err)
}
}
答案 1 :(得分:0)
下面的代码使用https://github.com/lib/pq
import (
"database/sql"
"fmt"
"github.com/lib/pq"
)
func bulkCopyTest() {
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=verify-full",
host, port, user, password, dbname)
db, err := sql.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
defer db.Close()
tx, err := db.Begin()
if err != nil {
panic(err)
}
stmt, err := tx.Prepare(pq.CopyInSchema("schemaName", "DBName", "columnName", "columnName"))
if err != nil {
panic(err)
}
//loop through an array of struct filled with data, or read from a file
for _, row := range loadCsv {
stmt.Exec(row.value1, row.value2)
if err != nil {
panic(err)
}
}
_, err = stmt.Exec()
if err != nil {
panic(err)
}
err = stmt.Close()
if err != nil {
panic(err)
}
err = tx.Commit()
if err != nil {
panic(err)
}
}