Sqlx获取准备好的语句

时间:2018-05-05 07:52:57

标签: postgresql go sqlx

我正在尝试使用预准备语句从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"`
}
我试过用BTW吗?而不是$ 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”:“scannable dest类型切片,结果中包含\ u003e1列(10)”,

在表中没有记录我试图删除除Account(struct)中的ID之外的所有字段,但它不起作用。

1 个答案:

答案 0 :(得分:1)

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

  

GetSelect在scannable类型和rows.StructScan上使用rows.Scan   不可扫描的类型。它们与QueryRow和Query大致相似,   其中Get对于获取单个结果并对其进行扫描非常有用   选择对于获取结果片段非常有用:

要获取单个记录,请使用Get

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

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

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,则在您的情况下。它会起作用。