Golang MySQL Simple package and use

Source: Internet
Author: User
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 ()

Related Article

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.