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

时间:2018-08-22 08:48:46

标签: go

需要帮助从数据库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:获得了54个参数,但该语句请求18

我哪里出错了? 谢谢。

1 个答案:

答案 0 :(得分:2)

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

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