本文介绍了使用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数组放入结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!