user2315094
user2315094

Reputation: 809

How to query and handle a UUID created with go.uuid and inserted into PostgreSQL 11?

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\n", 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

Upvotes: 1

Views: 3216

Answers (1)

snassr
snassr

Reputation: 1548

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\n", idn)

Upvotes: 4

Related Questions