1

我正在尝试使用准备好的语句从 postgress 表中获取一些数据

如果我尝试使用 database.Get() 一切都会返回。

桌子:

create table accounts
(
  id            bigserial not null
    constraint accounts_pkey
    primary key,
  identificator text      not null,
  password      text      not null,
  salt          text      not null,
  type          smallint  not null,
  level         smallint  not null,
  created_at    timestamp not null,
  updated       timestamp not null,
  expiry_date   timestamp,
  qr_key        text
);

账户结构:

type Account struct {
    ID            string `db:"id"`
    Identificator string `db:"identificator"`

    Password   string         `db:"password"`
    Salt       string         `db:"salt"`
    Type       int            `db:"type"`
    Level      int            `db:"level"`
    ExpiryDate time.Time      `db:"expiry_date"`
    CreatedAt  time.Time      `db:"created_at"`
    UpdateAt   time.Time      `db:"updated_at"`
    QrKey      sql.NullString `db:"qr_key"`
}

顺便说一句,我尝试使用?而不是 1 美元和 2 美元

stmt, err := database.Preparex(`SELECT * FROM accounts where identificator = $1 and type = $2`)

if err != nil {
    panic(err)
}
accounts := []account.Account{}
err = stmt.Get(&accounts, "asd", 123)
if err != nil {
    panic(err)
}

我得到的错误是

"errorMessage": "结果中带有 \u003e1 列 (10) 的可扫描 dest 类型切片",

在表中没有记录我试图从帐户(结构)中删除除 ID 之外的所有字段,但是它不起作用。

4

1 回答 1

2

sqlx 的文档将Get 和 Select描述为:

GetSelect在可扫描类型上使用 rows.Scan,在不可扫描类型上使用 rows.StructScan。它们大致类似于 QueryRow 和 Query,其中 Get 可用于获取单个结果并对其进行扫描,而 Select 可用于获取结果片段:

对于获取单个记录,请使用Get.

stmt, err := database.Preparex(`SELECT * FROM accounts where identificator = $1 and type = $2`)
var account Account
err = stmt.Get(&account, "asd", 123)

如果您的查询返回多条记录,请使用Selectwith 语句:

stmt, err := database.Preparex(`SELECT * FROM accounts where identificator = $1 and type = $2`)
var accounts []Account
err = stmt.Select(&accounts, "asd", 123)

在您的情况下,如果您stmt.Select改用 if stmt.Get。它会起作用的。

于 2018-05-05T08:05:54.893 回答