package main import ( "database/sql" _ "github.com/Go-SQL-Driver/MySQL" "log" ) func initMysql() *sql.DB { //打开数据库连接Open(驱动名,连接字符串) db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/test?charset=utf8") if err != nil { log.Fatal(err) } return db } func query() { db := initMysql() defer db.Close() row, err := db.Query("select * from user") if err != nil { log.Fatal(err) } var name string = "" var id int = 0 var password string = "" for row.Next() { row.Scan(&name, &id, &password) log.Println("id:", id, ",name:", name, "password:", password) } } func insert() { db := initMysql() defer db.Close() result, _ := db.Exec("insert into user values(?,?,?)", "test", 2, "test") c, _ := result.RowsAffected() log.Println("add affected rows:", c) } func delete() { db := initMysql() defer db.Close() result, _ := db.Exec("delete from user where id = ?", 2) c, _ := result.RowsAffected() log.Println("delete affected rows:", c) } func update() { db := initMysql() defer db.Close() result, _ := db.Exec("update user set password = ? where id = ?", "kk", 1) c, _ := result.RowsAffected() log.Println("update affected rows:", c) } func main() { insert() query() delete() update() }
有疑问加站长微信联系(非本文作者)