doucou19961205 2019-03-22 14:11
浏览 121
已采纳

如何查询和处理使用go.uuid创建并插入PostgreSQL 11的UUID?

I inserted in PostgreSQL table an UUID created with go.uuid :

import (
        "github.com/satori/go.uuid"
) 

func main() {
        usid := uuid.Must(uuid.NewV4())
        fmt.Println("usid := uuid.Must(uuid.NewV4")
        fmt.Println(usid.String())
        res, err := stmt.Exec(cn, csn, ccn, id)
        if err != nil || res == nil {
                log.Fatal(err)
        }
}

    sStmt := "insert into basicuserinfo (cn, csn, ccn, appUserAccountID ) 
    values ($1, $2, $3, $4)"
    stmt, err := db.Prepare(sStmt)
    if err != nil {
            log.Fatal(err)
    }
    defer stmt.Close()
    fmt.Println("# Inserting values")

And actually a row is inserted in the postgreSQL db:

           cn  |  csn  |  ccn | id
                              | 2412fcd3-8712-4a0f-830a-d77bd4cf2195      

In order to query with golang variables I tried first, to use a prepared statement. First, using db.PrepareContext :

    sel := "SELECT appUserAccountID FROM basicuserinfo WHERE cn = $1 AND csn 
    = $2 AND ccn = $3"

     stmt, err = db.PrepareContext(ctx,sel)
    if err != nil {
            log.Fatal(err)
    }
    var utenteID string
    err = stmt.QueryRowContext(ctx,cn, csn, ccn).Scan(&utenteID)
    log.Printf("ID= %s
", utenteID)
    fmt.Println("aaaaaaaaa") // Just to check that the this line gets executed

Whose execution remains "idle", in stand-by, without ending and producing any output:

marco@pc01:~/go/marcoGolang/goPostgres$ go run pqExample00.go
# Inserting values

Then I tried in this way, with db.Prepare():

    stmt, err = db.Prepare(sel)
    if err != nil {
            log.Fatal(err)
    }
    res, err = stmt.Exec(cnv, csnv, ccnv)

In this second case the execution seems ending successfully, but I do not know how to convert the sql.Result into a correct form which can be handled, for example simply displayed with fmt.Println() or getting other handlings. So... how to correctly query and handle a UUID created with go.uuid and inserted into PostgreSQL 11?

Looking forward to your kind help. Marco

  • 写回答

1条回答 默认 最新

  • douluan4644 2019-03-22 14:44
    关注

    Unless you have a reason for using PrepareContext, you could just do this?

    db, err := sql.Open("postgres", connectionString)
    
    sel := "SELECT appUserAccountID FROM basicuserinfo WHERE cn = $1 AND csn = $2 AND ccn = $3"
    
    var idn string
    err = db.QueryRow(sel, cn, csn, ccn).Scan(&idn)
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Printf("idn: %v
    ", idn)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失