我正在尝试从 CSV 向我的数据库中进行批量插入,并且可以插入单行,但显然批量插入会快得多。构建大规模查询很麻烦,所以我使用了https://godoc.org/github.com/huandu/go-sqlbuilder#InsertBuilder,它似乎正确地构建了查询和参数。
查询生成器和循环:
// prepare insert query
ib := sqlbuilder.NewInsertBuilder()
ib.InsertInto(tableName)
ib.Cols(columns)
// stream file line by line for db ingestion
scanner := csv.NewScanner(file, csv.Comma(','), csv.SkipRecords(1), csv.FieldsPerRecord(-1))
fmt.Println("Uploading data...")
for scanner.Scan() {
// split string by delimeter and trim whitespace if it's not the header row
if count > 0 {
record := scanner.Record()
recordValues := make([]interface{}, len(record))
for i, s := range record {
recordValues[i] = s
}
ib.Values(recordValues...)
}
count++
}
// convert batch to sql
sql, args := ib.Build()
fmt.Println(sql)
fmt.Println(args)
// execute batch
_, err = tx.Exec(sql, args...)
这个查询的输出是这样的(修剪,但看起来正确)
插入表名(第 1-23 列)值(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,? , ?, ?, ?), (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? , ?, ?), (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? , ?), (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ), ...
而且我什至不会发布 args,因为它是 34k 切片。
现在我们可以看到,所有准备好的语句?
都在那里,那么为什么 sqlx 返回这个错误:
2020/02/14 02:18:22 sql:预期 23 个参数,得到 34477
它似乎只将第一批插入视为准备好的语句,而忽略了其余的。