sqlx – 非结构目标类型的结构,具有>1列(2)

huangapple go评论89阅读模式
英文:

sqlx - non-struct dest type struct with >1 columns (2)

问题

我已经搜索了这个错误,并找到了两个相关的问题:

这是我的代码:

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)
	}

}

它创建了一个表并插入了两条记录,但无法将它们返回:

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

我该如何修复它?

英文:

I have searched the error and I have find two questions:

  • This one, but my question is not duplicate of it
  • And this one, but there is no answer in this question.

Here is my code:

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)
	}

}

It creates table and insert 2 records, but can not return them back:

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

How can I fix it ?

答案1

得分: 58

如果你导出你的字段,它就会起作用:

type Film struct {
    Code int
    Name string
}

注意大写字母(Code,而不是code)。

英文:

It works if you export your fields:

type Film struct {
    Code int
    Name string
}

Notice the uppercase (Code, not code).

huangapple
  • 本文由 发表于 2016年9月26日 19:55:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/39702192.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定