go - Mapping struct to mysql table, and binding row to struct -


this first script using go-sql-driver.

my mysql table (product) looks like:

id int name varchar(255) ismatch tinyint(1) created datetime 

i want load row table, , bind struct.

i have far:

package main  import (     "database/sql"     "fmt"     _ "github.com/go-sql-driver/mysql" )  type product struct {     id    int64   name  string   ismatch ??????????   created ????? }  func main() {     fmt.printf("hello, world!\n")      db, err := sql.open("mysql", "root:@/product_development")     defer db.close()      err = db.ping()     if err != nil {         panic(err.error()) // proper error handling instead of panic in app     }      rows, err := db.query("select * products id=1")     if err != nil {         panic(err.error()) // proper error handling instead of panic in app     }  } 

now need to:

1. datatype in go use tinyint , datetime? 2. how map rows product struct? 

what datatype in go use tinyint , datetime?

for hint types database/sql package using, have @ documentation database/sql.scanner, lists go types used within database/sql itself:

int64 float64 bool []byte string time.time nil - null values 

this lead try int64 ismatch , time.time created. believe in reality can use pretty sized int (maybe bool, you'd have check source) ismatch because can stored "without loss of precision." documentation go-mysql-driver explains need add parsetime=true dsn in order parse time.time automatically or use nulltime.

how map rows product struct?

it should pretty strightforward, using rows.scan, like:

var products []*product rows.next() {     p := new(product)     if err := rows.scan(&p.id, &p.name, &p.ismatch, &p.created); err != nil { ... }     products = append(products, p) } if err := rows.err() { ... } 

this scans columns fields of struct , accumulates them slice. (don't forget close rows!)


Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -