postgresql - 将客户端 UUID 转换为 SQL UUID

标签 postgresql go

我正在使用 go 和包 uuid 生成类型为 [16]byte 的 uuid。但是,当我尝试将该 uuid 插入类型为 uuidpostgres 列时,出现错误 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/

相关文章:

go - 为什么这个程序在 liteIde 中工作,但在从终端运行时因无效指针引用而崩溃?

go - 什么是 golang 中的上下文寄存器?

c++ - 直接使用 postgres JSONB

sql - 显示一行中的字段

sql - 如何在 CTE 或子查询中引用 DISTINCT 列名称?

go - 写入网络映射的驱动器时出现Fprintf错误

postgresql - 以与给定列表相同的顺序从 HQL 查询获取结果

postgresql - 将查询结果连接到 PostgreSQL 中的变量中

go - 在 go 中为多个处理程序设置 http header

algorithm - html模板中的golang乘法算法