package main import ( "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 } stmt , 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("select 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(){ if test.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 test, 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() } }
有疑问加站长微信联系(非本文作者)