Golang notes (1)-database query results mapped to struct

Source: Internet
Author: User

Common mapping mode

Query:="Selectfromuserwhere id=?"

A single structural body
ret:=&activity{}dbclient (). Find (Query,activityid). Unique (ret)
struct array
Ret:=[]activity{}
Dbclient (). Find (Query,activityid). List (&ret)

1. Define the structure body

struct {id Int64 ' col: 'ID' json:'ID'string ' col: 'name' JSON:'name' '}

2. Defining Database Objects

struct {    data       []map[string]string//    err        error                 exception }var prokdb *sql. Db

3. Pass the object address to the struct

Func (d *dao) Unique (inch Interface{}) error {ifLen (D.data) >0 {returnD.mapping (d.data[0], reflect. ValueOf (inch))}returnNil}func (d*dao) mapping (M map[string]string, v reflect. Value) Error {t:=V.type () Val:=V.elem () Typ:=T.elem ()if!val. IsValid () {returnErrors. New ("data type is incorrect")} forI: =0; I < Val. Numfield (); i++{value:=val. Field (i) Kind:=value. Kind () Tag:= Typ. Field (i). Tag.get ("Col")ifLen (TAG) >0{meta, OK:=M[tag]if!OK {Continue}if!value. Canset () {returnErrors. New ("struct field does not have read and write permissions")}ifLen (meta) = =0 {Continue}ifKind = =reflect. String {value. SetString (META)}Else ifKind = =reflect. Float32 {f, err:= StrConv. parsefloat (Meta, +)ifErr! =Nil {returnErr}value. SetFloat (f)}Else ifKind = =reflect. Float64 {f, err:= StrConv. parsefloat (Meta, -)ifErr! =Nil {returnErr}value. SetFloat (f)}Else ifKind = =reflect. Int64 {integer64, err:= StrConv. parseint (Meta,Ten, -)ifErr! =Nil {returnErr}value. Setint (INTEGER64)}Else ifKind = =reflect. Int {integer, err:=StrConv. Atoi (META)ifErr! =Nil {returnErr}value. Setint (Int64 (integer))}Else ifKind = =reflect. Bool {b, err:=StrConv. Parsebool (META)ifErr! =Nil {returnErr}value. Setbool (b)}Else {returnErrors. New ("unrecognized data types exist for database mappings")}}}returnNil}//Querying Datafunc (d*dao) Find (sqlstring, args ...Interface{}) *DAO {rows, err:=prokdb.query (sql, args ...)ifErr! =Nil {D.err=Errreturnd}defer rows. Close () Err=d.query (rows)ifErr! =Nil {D.err=Err}returnD}//mapping data to map[string]stringFunc (d *dao) query (rows *SQL. Rows) error {column, err:= Rows. Columns ()//read out the queried column field namesifErr! =Nil {logger. Error (ERR)returnerr}values:= Make ([]byte, Len (column))//values is the value of each column, which is obtained in ByteScans: = Make ([]Interface{}, Len (column))//because each query comes out of an indeterminate column, the length of the query is fixed with Len (column) forI: =range Values {Scans[i]= &Values[i]}results:= Make ([]map[string]string,0)//finally get the map forrows. Next () {ifERR: = rows. Scan (Scans ...); Err! =Nil {//query. The indefinite Long value of the scan query is placed in scans[i] = &values[i], i.e. each line is placed in the valueslogger. Error (ERR)returnErr}row:= Make (map[string]string)//each row of data forK, V: =Range Values {//each row of data is placed in the values, now move it to the rowKey: =Column[k]row[key]=string(v)}results=Append (results, row)}d.data=ResultsreturnNil}//pass the object address outFunc (d *dao) Unique (inch Interface{}) error {ifLen (D.data) >0 {returnD.mapping (d.data[0], reflect. ValueOf (inch))}returnNil}
Func (d *dao) List (inch Interface{}) error {ifD.err! =Nil {returnD.err} Length:=Len (d.data)ifLength >0{V:= Reflect. ValueOf (inch). Elem () NEWV:= Reflect. Makeslice (V.type (),0, Length) v.set (NEWV) v.setlen (length) Index:=0         forI: =0; i < length; i++{k:=V.type (). Elem (). Elem () NEWOBJ:=reflect. New (k) Err:=d.mapping (D.data[i], NEWOBJ)ifErr! =Nil {returnErr} v.index (Index). Set (NEWOBJ) Index++} v.setlen (index)}returnNil}

Golang notes (1)-database query results mapped to struct

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.