我正在使用 go
和包 uuid
生成类型为 [16]byte
的 uuid。但是,当我尝试将该 uuid 插入类型为 uuid
的 postgres
列时,出现错误 converting argument $1 type: unsupported type [16]uint8, a array
。所以显然我应该在将它插入数据库之前转换客户端上的 uuid。我该怎么做?我应该将其转换为什么类型?
简而言之:在 postgres
中,什么 go
数据类型可以与 uuid
一起使用?
最佳答案
感谢来自@sberry 的链接,我找到了成功。以下是有益于您的代码片段(使用 PostgreSQL 9.5 数据库):
import (
"database/sql"
"net/http"
"github.com/google/uuid"
)
type Thing struct {
ID uuid.UUID `json:"-" sql:",type:uuid"`
Name string `json:"name"`
}
// For a database table created as such:
// CREATE TABLE things (
// id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
// name TEXT DEFAULT ''::text
// )
func selectThingssSQL() ([]Thing, error) {
things := make([]Thing, 0)
rows, err := db.Query("SELECT id, name FROM things")
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
t := &Thing{}
if err := rows.Scan(&t.ID, &t.Name); err != nil {
return nil, err
}
things = append(things, *t)
}
return things, nil
}
关于postgresql - 将客户端 UUID 转换为 SQL UUID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48479264/