【问题标题】:Sqlx Get with prepared statementsSqlx 使用准备好的语句获取
【发布时间】:2018-05-08 17:06:57
【问题描述】:

我正在尝试使用准备好的语句从 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 之外的所有字段,但是它不起作用。

【问题讨论】:

  • 直接在 pgadmin 中运行 prepare 中的查询。检查它返回多少行或它返回单行。因为Get是用来选择单条记录的。

标签: postgresql go sqlx


【解决方案1】:

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

GetSelect 在可扫描类型和 rows.StructScan 上使用 rows.Scan 不可扫描的类型。它们大致类似于 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)

如果您的查询返回多条记录,请使用Select with statement as:

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

如果您使用stmt.Select 而不是stmt.Get,则在您的情况下。它会起作用的。

【讨论】:

  • 它对我们有用,但我们使用 : 而不是 $
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多