drvxclagw656708070 2017-06-06 00:58
浏览 98
已采纳

使用StructScan将PostgreSQL数组放入结构

Test data:

CREATE TABLE test (id int, data text[])
INSERT INTO test(id, data) VALUES(1, '{a,b,c}')

Go Code. First - one that is working just fine:

func main() {
  db, _ := sqlx.Open("postgres", "user=postgres dbname=test sslmode=disable")
  var id int
  var asSlice []string
  err := db.QueryRowx(`SELECT id, data FROM test WHERE data @> ARRAY['b']`).Scan(&id, pq.Array(&asSlice))
  if err != nil {
    log.Fatal(err)
  }
  fmt.Println(id, asSlice)
}

I get 1 [a b c] as expected. But here I manually assign results to the variables

Now, to the part that is not working - using StructScan

type MyStruct struct {
    Id   int
    Data []string
}

func main() {
    db, _ := sqlx.Open("postgres", "user=postgres dbname=test sslmode=disable")
    var testStruct MyStruct
    err := db.QueryRowx(`SELECT id, data FROM test WHERE data @> ARRAY['b']`).StructScan(&testStruct)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(testStruct)
}

sql: Scan error on column index 1: unsupported Scan, storing driver.Value type []uint8 into type *[]string

I guess that means that sqlx does not know about PostgreSQL arrays and does not use pq.Array internally.

What should I do about it? Maybe I am doing something wrong? Or maybe I should apply pq.Array manually? If so - how?

  • 写回答

1条回答 默认 最新

  • dsstlsqt696435 2017-06-06 09:05
    关注

    Try using pq.StringArray type for []string

    type MyStruct struct {
        Id   int
        Data pq.StringArray
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备