duanfen7676 2018-05-05 07:52
浏览 251
已采纳

Sqlx使用准备好的语句获取

I am trying to fetch some data from postgress table using prepared statements

If I try with database.Get() everything is returned.

Table:

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

Account struct:

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 i tried using ? instead of $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)
}

The error I get is

"errorMessage": "scannable dest type slice with \u003e1 columns (10) in result",

In the table there are no records I tried to remove all fields except the ID from Account (struct), however it does not work.

  • 写回答

1条回答 默认 最新

  • douzhi2760 2018-05-05 08:05
    关注

    Documentation for sqlx described Get and Select as:

    Get and Select use rows.Scan on scannable types and rows.StructScan on non-scannable types. They are roughly analagous to QueryRow and Query, where Get is useful for fetching a single result and scanning it, and Select is useful for fetching a slice of results:

    For fetching a single record use Get.

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

    If your query returns more than a single record use 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)
    

    In your case if you use stmt.Select instead if stmt.Get. It will work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥15 python天天向上类似问题,但没有清零
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?