gpt4 book ai didi

go - 检索后无法将数据插入数据库

转载 作者:数据小太阳 更新时间:2023-10-29 03:45:48 26 4
gpt4 key购买 nike

需要帮助从数据库 ms sql 中提取数据并将它们添加到数据库 postgres。数据提取成功。但是插入问题。我无法将界面分解为 18 个。

package main

import (
"database/sql"
"fmt"
"io/ioutil"
"log"

_ "github.com/denisenkom/go-mssqldb"
_ "github.com/lib/pq"
)

const (
// config to connect to ms sql server

// config to connect to PostgreSQL

)

func main() {
connStringmssql := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d;database=%s;", server, user, password, port, database)
db, err := connect("mssql", connStringmssql)
checkError("Error mssql connect function ", err)
defer db.Close()
defer fmt.Printf("Disconnected mssql!\n")

connStringpg := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=%s", serverpg, portpg, userpg, passwordpg, databasepg, "disable")
dbpg, err := connect("postgres", connStringpg)
checkError("Error connect function pg ", err)
defer dbpg.Close()
defer fmt.Printf("Disconnected pg!\n")

// Read sql query from file and convert it
mssqlSelectQueryUnConvert, err := ioutil.ReadFile("./sql/mssqlSelect.sql")
checkError("Error read sql file", err)
mssqlSelectQuery := string(mssqlSelectQueryUnConvert)

rows, err := db.Query(mssqlSelectQuery)
checkError("Error in sql query ", err)
defer rows.Close()
columnNames, err := rows.Columns()
checkError("Error sql columns names ", err)

objects := make([]interface{}, len(columnNames))
objectsScan := make([]interface{}, len(columnNames))
rest := make([]interface{}, len(columnNames))
for i := range objects {
objectsScan[i] = &objects[i]
}

for rows.Next() {
err = rows.Scan(objectsScan...)
if err != nil {
fmt.Println("Failed to scan row", err)
return
}
rest = append(rest, objects...)
}
fmt.Println(rest)

dbInsert, err := dbpg.Exec("INSERT INTO object_test (column1...column18) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)", rest...)
checkError("Error dbpg insert ", err)
fmt.Println(dbInsert.RowsAffected())
}

我得到错误:错误 dbpg insert pq: got 54 parameters but the statement requests 18

我哪里错了?谢谢。

最佳答案

您将所有行连接到一个 rest 变量中,然后尝试将它们全部插入到 Postgres 中的单个行中。这显然行不通。

您可能需要将您的 db.Insert 语句移动到您的 rows.Next() 循环中,并且每行执行一次插入。

关于go - 检索后无法将数据插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51963049/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com