This is a creation in Article, where the information may have evolved or changed.
Sometimes it's really not necessary to use Xorm to gorm these heavyweight ORM tools.
Golang had a well-established MySQL library, and it was really much better than the MySQL Library of node. JS, which is anti-human and dabbler.
Open MySQL
Import ("Database/sql" _ "Github.com/go-sql-driver/mysql") Dbtemp, err:= SQL. Open ("MySQL","Root:password@/dbname?charset=utf8") DB=dbtempifErr! =Nil {fmt. PRINTLN (Err)} stmt, err:= db. Prepare ("CREATE table if not exists dev (ID int. UNSIGNED auto_increment not NULL PRIMARY key,uid varchar (+), did varchar, NA Me varchar, qid varchar (+), status char DEFAULT ' u ')") ifstmt! =Nil {stmt. Exec () stmt. Close ()} stmt, err:= db. Prepare ("ALTER TABLE Dev convert to character set UTF8 collate utf8_general_ci")//to modify the encoding ifstmt! =Nil {stmt. Exec () stmt. Close ()} _=Err
Encapsulates a function
This function returns a row of data as a []string]. If a column data is empty, it is an empty string. The error returns nil.
Func getone (Rows *sql. Rows) []string { ifrows = =Nil {returnNil} cols, err:=rows. Columns () Rawresult:= Make ([]byte, Len (cols)) Result:= Make ([]string, Len (cols)) Dest:= Make ([]Interface{}, Len (cols)) forI, _: =range Rawresult {dest[i]= &rawresult[i] } ifrows. Next () {Err=rows. Scan (dest ...) forI, raw: =Range Rawresult {ifRaw = =Nil {result[i]="" } Else{Result[i]=string(Raw)}} //FMT. Printf ("% #v \ n", result)// Break}Else { returnNil} _=Errreturnresult}
Then you can use
stmt, err: = db. Prepare ("select Did,name from Dev where (uid=? and name=?) " ) Printerr (ERR) rows, err:= stmt. Query (r.fromusername, name) Printerr (ERR) Re:= getone (rows) stmt. Close ()
stmt, err: = db. Prepare ("insert INTO dev (uid,did,name,qid) VALUES (?,?,?,?) " ) stmt. Exec (R.fromusername,r.deviceid,con,r.tousername) stmt. Close ()