dongzhan1570 2018-01-27 18:43
浏览 308
已采纳

将客户端UUID转换为SQL UUID

I'm using go and the package uuid to generate a uuid of type [16]byte. However when I try to insert that uuid into my postgres column of type uuid I get the error converting argument $1 type: unsupported type [16]uint8, a array. So apparently I should convert the uuid on the client before I insert it into the db. How should I do that? What type should I convert it to?

In short: What go data type will work with uuid in postgres?

  • 写回答

1条回答 默认 最新

  • dongxie3963 2018-12-15 19:21
    关注

    Thanks to the link from @sberry, I found success. Here are snippets of the code for your benefit (with a PostgreSQL 9.5 database):

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料