Go使用Gin寫一個對MySQL的增刪改查的實現(xiàn)
首先用SQL創(chuàng)建一個包含id、name屬性的users表
create table users ( id int auto_increment primary key, name varchar(255) null );
查詢所有用戶信息:
func queryData(db *sql.DB, w http.ResponseWriter) { rows, err := db.Query("SELECT * FROM users") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer rows.Close() var users []struct { ID int `json:"id"` Name string `json:"name"` } for rows.Next() { var id int var name string err := rows.Scan(&id, &name) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } users = append(users, struct { ID int `json:"id"` Name string `json:"name"` }{id, name}) } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(users) }
根據(jù)姓名插入一個用戶信息
func insertData(db *sql.DB, name string, w http.ResponseWriter) { stmt, err := db.Prepare("INSERT INTO users(name) VALUES(?)") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer stmt.Close() res, err := stmt.Exec(name) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } id, _ := res.LastInsertId() w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]int64{"id": id}) }
根據(jù)id刪除一個用戶信息
func deleteData(db *sql.DB, id int, w http.ResponseWriter) { stmt, err := db.Prepare("DELETE FROM users WHERE id=?") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer stmt.Close() res, err := stmt.Exec(id) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } affected, _ := res.RowsAffected() w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]int64{"deleted": affected}) }
三個方法整合一起放到main.go文件里
package main import ( "database/sql" "encoding/json" "log" "net/http" "strconv" _ "github.com/go-sql-driver/mysql" "github.com/gorilla/mux" ) func main() { db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/test_go") if err != nil { log.Fatal(err) } defer db.Close() r := mux.NewRouter() r.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: queryData(db, w) case http.MethodPost: var user struct{ Name string } if err := json.NewDecoder(r.Body).Decode(&user); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } insertData(db, user.Name, w) } }).Methods("GET", "POST") r.HandleFunc("/insert", func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } var user struct{ Name string } if err := json.NewDecoder(r.Body).Decode(&user); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } insertData(db, user.Name, w) }).Methods("POST") r.HandleFunc("/users/{id}", func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) idStr := vars["id"] id, err := strconv.Atoi(idStr) if err != nil { http.Error(w, "Invalid ID", http.StatusBadRequest) return } deleteData(db, id, w) }).Methods("DELETE") log.Println("Server running at http://localhost:8083") log.Fatal(http.ListenAndServe(":8083", r)) } func queryData(db *sql.DB, w http.ResponseWriter) { rows, err := db.Query("SELECT * FROM users") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer rows.Close() var users []struct { ID int `json:"id"` Name string `json:"name"` } for rows.Next() { var id int var name string err := rows.Scan(&id, &name) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } users = append(users, struct { ID int `json:"id"` Name string `json:"name"` }{id, name}) } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(users) } func insertData(db *sql.DB, name string, w http.ResponseWriter) { stmt, err := db.Prepare("INSERT INTO users(name) VALUES(?)") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer stmt.Close() res, err := stmt.Exec(name) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } id, _ := res.LastInsertId() w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]int64{"id": id}) } func deleteData(db *sql.DB, id int, w http.ResponseWriter) { stmt, err := db.Prepare("DELETE FROM users WHERE id=?") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer stmt.Close() res, err := stmt.Exec(id) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } affected, _ := res.RowsAffected() w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]int64{"deleted": affected}) }
1. 添加mysql的依賴
go get -u github.com/go-sql-driver/mysql
2. 添加gin的依賴
go get -u github.com/gin-gonic/gin
3. 添加對gorm的依賴
go get -u gorm.io/gorm
go.mod文件
module go-backend go 1.24.0 require ( github.com/go-sql-driver/mysql v1.9.2 github.com/gorilla/mux v1.8.1 ) require filippo.io/edwards25519 v1.1.0 // indirect
然后啟動
go run main.go
獲取用戶數(shù)據(jù)
http://localhost:8083/users
插入用戶數(shù)據(jù)
http://localhost:8083/users
刪除用戶數(shù)據(jù)
http://localhost:8083/users/4
到此這篇關(guān)于Go使用Gin寫一個對MySQL的增刪改查的實現(xiàn)的文章就介紹到這了,更多相關(guān)Gin MySQL增刪改查內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
GOPROXY:解決go get golang.org/x包失敗問題
這篇文章主要介紹了GOPROXY:解決go get golang.org/x包失敗問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01golang 的string與[]byte轉(zhuǎn)換方式
這篇文章主要介紹了golang 的string與[]byte轉(zhuǎn)換方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04Windows10系統(tǒng)下安裝Go環(huán)境詳細步驟
Go語言是谷歌推出的一款全新的編程語言,可以在不損失應(yīng)用程序性能的情況下極大的降低代碼的復雜性,這篇文章主要給大家介紹了關(guān)于Windows10系統(tǒng)下安裝Go環(huán)境的詳細步驟,需要的朋友可以參考下2023-11-11