使用StructScan将PostgreSQL数组放入结构

编程入门 行业动态 更新时间:2024-10-27 07:18:20
本文介绍了使用StructScan将PostgreSQL数组放入结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

测试数据:

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

我得到了 1 [abc] 的期望值。 但是这里我将结果手动分配给变量

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

现在,将结果分配给不起作用的部分-使用StructScan

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

我想这意味着sqlx不了解PostgreSQL数组并且不使用 pq .Array 内部。

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

我该怎么办?也许我做错了什么?还是我应该手动应用 pq.Array ?

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

推荐答案

尝试将 pq.StringArray 类型用于[] string

Try using pq.StringArray type for []string

type MyStruct struct { Id int Data pq.StringArray }

更多推荐

使用StructScan将PostgreSQL数组放入结构

本文发布于:2023-10-26 11:40:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1530031.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   放入   结构   StructScan   PostgreSQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!