Home > OS >  Golang: how to proper handle dynamic select query
Golang: how to proper handle dynamic select query

Time:04-09

what's the best way to handle the result of a select sql query in go?

Context(thats what i got so far...):

@Update

func (s *SQLServiceServer) select_query_func() {
    
    // db_connection and validation

    rows, err1 := db.Query(request.GetQuery())

    if err1 != nil {
        panic(err1)
    }

    defer rows.Close()

    columns, err2 := rows.Columns()

    if err2 != nil {
        panic(err2)
    }

    // Loop through rows, using Scan to assign column data to struct fields.
    for rows.Next() {
        values := make([]interface{}, len(columns))

        for i := range values {
            values[i] = new(interface{})
        }
        if err2 = rows.Scan(values...); err2 != nil {
            panic(err2)
        }

        for i := range values {
            fmt.Println(values[i])
        }
    }

    return requestOutput(REQUEST_OK, RESULT_OK, ERROR_NULL)
}

To sumarize, what's the best approach to do it?

The error that i mentioned

error

CodePudding user response:

Scan requires allocated, i.e. non-nil, pointers as arguments. The following types are allowed:

*string
*[]byte
*int, *int8, *int16, *int32, *int64
*uint, *uint8, *uint16, *uint32, *uint64
*bool
*float32, *float64
*interface{}
*RawBytes
*Rows (cursor value) any type implementing Scanner (see Scanner docs)

So to fix your code you need to populate the values slice with non-nil pointers, and for your purpose those pointers can be of type *interface{}.

for rows.Next() {
    values := make([]interface{}, len(columns))
    for i := range values {
        values[i] = new(interface{})
    }
    if err := rows.Scan(values...); err != nil {
        return err
    }
}
  • Related