Go MySQL Use example

Source: Internet
Author: User

Download MySQL Driver
$ go get github.com/go-sql-driver/mysql

or download source stacking to Gopath,: Https://github.com/go-sql-driver/mysql

Example

Build table

Simply create a table tbl_log containing 3 fields Ip,name, detail_msg.

The following code inserts a record into the table.

package mainimport (    "database/sql"    "fmt"    "log"    _ "github.com/go-sql-driver/mysql")var DB *sql.DBvar dataBase = "root:[email protected](127.0.0.1:3306)/new_portal?loc=Local&parseTime=true"func Init() {    var err error    DB, err = sql.Open("mysql", dataBase)    if err != nil {        log.Fatalln("open db fail:", err)    }    DB.SetMaxOpenConns(20)    DB.SetMaxIdleConns(15)    err = DB.Ping()    if err != nil {        log.Fatalln("ping db fail:", err)    }}func main() {    Init()    insert()}func insert() {    origin := "abc"    log.Println("orign:",origin)    detailMsg := origin    sql := fmt.Sprintf(        "insert into tbl_log(ip, name, detail_msg) values (‘%s‘, ‘%s‘, ‘%s‘)",        "1.1.0.1",        "test.py",        detailMsg,    )    log.Println("sql:", sql)    _, err := DB.Exec(sql)    if err != nil {        log.Println("exec failed:", err, ", sql:", sql)        return    }}

Output

2018/04/06 10:17:00 ORIGN:ABC
2018/04/06 10:17:00 Sql:insert into Tbl_log (IP, name, detail_msg) VALUES (' 1.1.0.1 ', ' test.py ', ' abc ')

View the database and insert the record.

Go MySQL Use example

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.