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 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号