SQL in Go

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Official SQL

func main() {type Userinfo struct {Id uintUsername stringDepartment stringCreated string}db, err := sql.Open("mysql","root:root@tcp(localhost:3306)/gorm")if err != nil {log.Fatal(err.Error())}defer db.Close()//准备语句,避免多次重复执行stmt,err := db.Prepare("INSERT userinfo SET username=?,department=?,created = ?")if err != nil {log.Fatal(err.Error())}res,err := stmt.Exec("lisi","ad",time.Time{})if err != nil {log.Fatal(err.Error())}log.Println(res )rows,err := db.Query("SELECT * FROM userinfo")if err != nil {log.Fatal(err.Error())}var userinfo Userinfofor rows.Next() {rows.Scan(&userinfo)}}

Gorp

Type Product struct {Id int64 ' db: ' product_id ' ' PName string ' db: ' PName ' ' Price int ' db: ' Price ' '}func main () {db, err : = SQL. Open ("MySQL", "root:root@tcp (localhost:3306)/gorm") if err! = Nil {log. Fatal (Err. Error ())}defer db. Close ()//Official SQL--Gorpdbmap: = &gorp. Dbmap{db:db,dialect:gorp. mysqldialect{"Innnodb", "UTF8"}}dbmap. Createtablesifnotexists ()//log processing Dbmap. TraceOn ("[Gorp]", log. New (OS. Stdout, "app", log. Lmicroseconds) Product: = product{11101, "Taozi", 2000}dbmap. Insert (&product) dbmap. Delete (&product) var products []product_, err = Dbmap. Select (&products, "SELECT * from Product") var prod producterr = dbmap. SelectOne (&prod, "SELECT * from product where product_id=?", 3) fmt. PRINTLN ("Product:", prod)//support for native result, err: = Dbmap. Exec ("Delete from seller where seller_id=?", 2) log. Println (result. Rowsaffected ())}func Inserttrans (Dbmap *gorp. Dbmap, product *product) error {trans, err: = Dbmap. Begin () if err! = Nil {return Err}trans. Insert (product) return Trans.commit ()//if Commint is sucdessful, a nil error is returned} 

Gorm

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.