小编典典

sql:“扫描”中应有3个目标参数,而Golang中不应有1个

go

我的第一个代码是

package main

import (
    "fmt"
)

type BA_Client struct {
    ClientId    int    `json:ClientId;"`
    CompanyName string `json:CompanyName;"`
    CreateDate  string `json:CreateDate;"`
}

func main() {

    conn, _ := getConnection() // Det database connection

    query := `select * from IMBookingApp.dbo.BA_Client
              ORDER BY
                ClientId ASC
              OFFSET 56 ROWS
              FETCH NEXT 10 ROWS ONLY ;`

    var p []byte
    err := conn.QueryRow(query).Scan(&p)
    if err != nil {
        fmt.Println("Error1", err)
    }

    fmt.Println("Data:", p)

    var m BA_Client
    err = json.Unmarshal(p, &m)
    if err != nil {
        fmt.Println("Error2", err)
    }

}

我的第二个代码是

conn, _ := getConnection()
query := `select * from IMBookingApp.dbo.BA_Client__c
          ORDER BY
            ClientId__c ASC
          OFFSET 56 ROWS
          FETCH NEXT 10 ROWS ONLY ;`

rows, err := conn.Query(query)
if err != nil {
    fmt.Println("Error:")
    log.Fatal(err)
}

println("rows", rows)

defer rows.Close()

columns, err := rows.Columns()
fmt.Println("columns", columns)

if err != nil {
    panic(err)
}

for rows.Next() {
    receiver := make([]*string, len(columns))

    err := rows.Scan(&receiver )
    if err != nil {
        fmt.Println("Error reading rows: " + err.Error())
    }
    fmt.Println("Data:", p)

    fmt.Println("receiver", receiver)
}

使用这两个代码,我得到如下相同的错误

sql: expected 3 destination arguments in Scan, not 1

可能是因为我使用的是SQL Server,而不是MySQL?感谢是否有人可以帮助我找到问题。


阅读 245

收藏
2020-07-02

共1个答案

小编典典

当您要使用输入切片进行行扫描时,请使用可变的3点表示法...将切片转换为单独的参数,如下所示:

err := rows.Scan(receiver...)

使用可变参数的您的列(在本例中为三列)将有效地扩展为:

// len(receiver) == 3
err := rows.Scan(receiver[0], receiver[1], receiver[2])

编辑

SQL Scan方法的参数值必须为类型interface{}。因此,我们需要一个中间片。例如:

is := make([]interface{}, len(receiver))
for i := range is {
    is[i] = receiver[i]

    // each is[i] will be of type interface{} - compatible with Scan()
    // using the underlying concrete `*string` values from `receiver`
}

// ...

err := rows.Scan(is...)

// `receiver` will contain the actual `*string` typed items
2020-07-02