This is a creation in Article, where the information may have evolved or changed.
Package Mainimport ("FMT" "Database/sql" _ "Github.com/go-sql-driver/mysql") type testmysql struct {db * sql. Db}func Init () (*testmysql, error) {test: = new (TESTMYSQL) db, err: = SQL. Open ("MySQL", "Root: @tcp (172.16.3.8:3306)/jackma?charset=utf8") if err! = Nil {fmt. Println (Err. Error ()) return test,nil} test.db = db return Test, Nil}func (test* testmysql) Create () {if test.db = nil {return} St MT, Err: = Test.db.Prepare ("INSERT into test (name, id) VALUES (?,?)") If err! = Nil {fmt. Println (Err. Error ()) return} defer stmt. Close () If result, err: = stmt. Exec ("Jack", 20); Err = = Nil {if id, err: = result. Lastinsertid (); Err = = Nil {fmt. PRINTLN ("Insert ID:", id)}} If result, err: = stmt. Exec ("Jack2", 30); Err = = Nil {if id, err: = result. Lastinsertid (); Err = = Nil {fmt. PRINTLN ("Insert ID:", id)}} If result, err: = stmt. Exec ("Jack3", 40); Err = = Nil {if id, err: = result. Lastinsertid (); Err = = Nil {fmt. PRINTLN ("Insert ID:", id)}} If result, err: = stmt. Exec ("JacK4 ", 60); Err = = Nil {if id, err: = result. Lastinsertid (); Err = = Nil {fmt. PRINTLN ("Insert ID:", id)}}}func (Test *testmysql) Update () {if (test.db = = nil) {return} stmt, err: = Test.db.Prepare ( "Update test set name =?" WHERE id =? ") If err! = Nil {fmt. Println (Err. Error ()) return} defer stmt. Close () If result, err: = stmt. Exec ("jackma4888", 60); Err = = Nil {if c, err: = result. Rowsaffected (); Err = = Nil {fmt. PRINTLN ("Update Count:", c)}}}func (test* testmysql) Read () {if test.db = = nil{return} rows, err: = Test.db.Query ("se Lect ID, name from test ") if err! = Nil {fmt. Println (Err. Error ()) return} defer rows. Close () fmt. Println ("") clos, _: = Rows. Columns () for I: = range clos {fmt. Print (Clos[i]) fmt. Print ("\ t")} FMT. Println ("") var ID int; var name string; For rows. Next () {if err: = rows. Scan (&id, &name); Err! = Nil {fmt. Print (ID) fmt. Print ("\ t") fmt. Print (name) fmt. Print ("\ t") fmt. Print ("\t\r\n")}}}func (Test *testmysql) Delete () {ifTest.db = = nil{return} stmt, err: = Test.db.Prepare ("Delete from Test where id =?") If err! = Nil {fmt. Println (Err. Error ()) return} defer stmt. Close () If result, err: = stmt. Exec (20); Err = = Nil {if c, err: = result. Rowsaffected (); Err = = Nil {fmt. Println ("Delete count:", c)}}}func (Test *testmysql) Close () {if test.db! = nil {test.db.Close ()}}func main () {if TES T, err: = Init (); Err = = Nil {fmt. Println ("Create:") test. Create () fmt. Println ("UPDATE:") test. Update () fmt. Println ("read:") test. Read () fmt. Println ("Delete:") test. Delete () test. Read () fmt. Println ("Close:") test. Close ()}}