24

我搜索了错误,发现了两个问题:

  • 这个,但我的问题不是重复的
  • 还有这个,但是这个问题没有答案。

这是我的代码:

package main

import (
    "log"

    "github.com/jmoiron/sqlx"

    _ "github.com/lib/pq"
)

var schema = `
CREATE TABLE films (
  code int,
  name VARCHAR(10)
)`

type Film struct {
    code int
    name string
}

func main() {
    db, err := sqlx.Open("postgres", "user=demas password=root host=192.168.99.100 port=32768 dbname=mydb sslmode=disable")
    if err != nil {
        log.Fatal(err)
    }

    db.MustExec(schema)

    tx := db.MustBegin()
    tx.MustExec("INSERT INTO films(code, name) VALUES($1, $2)", 10, "one")
    tx.MustExec("INSERT INTO films(code, name) VALUES($1, $2)", 20, "two")
    tx.Commit()

    films := []Film{}
    err = db.Select(&films, "SELECT * FROM public.films")
    if err != nil {
        log.Fatal(err)
    }

}

它创建表并插入 2 条记录,但不能将它们返回:

λ go run main.go
2016/09/26 14:46:04 non-struct dest type struct with >1 columns (2)
exit status 1

我该如何解决?

4

1 回答 1

52

如果您导出字段,它会起作用:

type Film struct {
    Code int
    Name string
}

请注意大写字母 ( Code, not code)。

于 2016-09-26T12:55:55.323 回答