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