1.提早條件mysql
2.打開cmd命令行執行安裝命令git
go get github.com/Go-SQL-Driver/MySQL
3.查看是否安裝成功github
查看GOPATH下面是否有src目錄和pkg目錄,且裏面有找到MySQL,說明安裝成功sql
4.程序測試數據庫
package main // 導入包 import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" ) // mysql基本連接信息 var ( // 數據庫 host host = "127.0.0.1" // 數據庫用戶名 username = "xxx" // 數據庫密碼 password = "xxx" // 數據庫名 name = "xxx" ) func main() { // 連接數據庫 db, err := sql.Open("mysql", username+":"+password+"@tcp("+host+")/"+name+"?charset=utf8") if err != nil { panic(err) } // 查詢 rows, err := db.Query("select id,gender,username from users order by id asc") if err != nil { panic(err) } for rows.Next() { var id int var gender int var username string err = rows.Scan(&id, &gender, &username) if err != nil { panic(err) } fmt.Println(id, gender, username) } // 更新操做 updateStmt, err := db.Prepare("update users set gender=1 where id in (?,?)") if err == nil { res, err := updateStmt.Exec(2, 3) if err == nil { fmt.Println(res.RowsAffected()) // 返回受影響的行數 2 } } // 添加操做 insertStmt, err := db.Prepare("insert into regions (`id`,`parent_id`,`code`,`name`) values (?,?,?,?)") if err == nil { res, err := insertStmt.Exec(3514, 0, 830000, "南極") if err == nil { fmt.Println(res.LastInsertId()) // 返回插入成功最後的id 3514 } } // 刪除操做 deleteStmt, err := db.Prepare("delete from regions where id = ?") if err == nil { res, err := deleteStmt.Exec(3514) if err == nil { fmt.Println(res.RowsAffected()) // 返回受影響的行數 1 } } rows.Close() db.Close() }