I am doing a WS
, where I make a query to the database, as the database to which I made the query is Informix
, the connection was made through ODBC
, the problem that I have is when creating the json
due to the variable types , I appreciate the help.
To perform the query and extract the mapping, I am guiding myself through this example that of enters gives me the following result:
Imported packages:
import (
_"unicode/utf8"
_"os"
_ "github.com/alexbrainman/odbc"
"database/sql"
"fmt"
"os"
"time"
"reflect"
"log"
)
-code:
db, err := sql.Open("odbc", "DSN=" + host)
if err != nil {
fmt.Println("Could not connect to db:", err)
os.Exit(1)
}
err = db.Ping()
if err != nil {
fmt.Println("got an error:", err)
os.Exit(1)
}
/*SELECT*/
rows, err := db.Query("SELECT su.coduser AS id , TRIM(su.nomuser) AS user, s.fchven AS fch_ven, s.fecreg AS fch_registro FROM suser su JOIN sinfo s ON s.coduser = su.coduser WHERE su.nomuser=? AND su.pass=?",user_login,pass_login)
cols, _ := rows.Columns()
for rows.Next() {
// Create a slice of interface{}'s to represent each column,
// and a second slice to contain pointers to each item in the columns slice.
columns := make([]interface{}, len(cols))
columnPointers := make([]interface{}, len(cols))
for i, _ := range columns {
columnPointers[i] = &columns[i]
}
// Scan the result into the column pointers...
if err := rows.Scan(columnPointers...); err != nil {
//return err
}
// Create our map, and retrieve the value for each column from the pointers slice,
// storing it in the map with the name of the column as the key.
m := make(map[string]interface{})
for i, colName := range cols {
val := columnPointers[i].(*interface{})
m[colName] = *val
}
// Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
fmt.Print(m)
}
The query is fine, I actually do the cycle in case of several records, but when I print the map
to see it in console, it shows me the following result:
map[id:769244 user:[65 100 109 105 110 95 117 115 101 114] fch_ven:2019-11-06 00:00:00 -0500 -05 fch_registro:2017-04-15 05:05:29 -0500 -05]2018/05/25 15:06:42 {0 <nil> 0 0 0 0 0 0 0 0 }
I know I can do this:
var name string
if err := rows.Scan(&name); err != nil {
log.Fatal(err)
}
Create the variables and associate them, but I have problems with the fields that are of DATE
and DATETIME
, just do not return the information, so choose to use the example mentioned but I have problems with string
, aside from when I do the storage in a variable var test string = m["user"].(string)
. It just gives me an error in the line when I'm executing it, it just tells me that there is an error but it does not specify me.