社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
In this tutorial, we are going to see an example program to learn how to do database CRUD operations using Golang and MySQL. CRUD is an acronym for Create, Read, Update, and Delete. CRUD operations are basic data manipulation for database.
In this example, we are going to create an interface as database front end to handle these operations. We have Employee table containing Employee information like id, name and city. With this table, we have to perform CRUD using MySQL.
Step 1: Prepare and Import MySQL driver into your project
Using Git Bash first install driver for Go's MySQL database package. Run below command and install MySQL driver's
go get -u github.com/go-sql-driver/mysql
Now create Goblog Database
1. Open PHPMyAdmin/SQLyog or what ever MySQL database management tool that you are using.
2. Create a new database "goblog"
Step 2: Creating the Employee Table
Execute the following SQL query to create a table named Employee inside your MySQL database. We will use this table for all of our future operations.
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
`id` int(6) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
`city` varchar(30) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
Step 3: Creating Struct, Handler and Handler Function
Let's create a file named main.go and put the following code inside it.
We usually import database/sql and use sql to execute database queries on the database.
Function dbConn opens connection with MySQL driver.
We will create Employee struct that has following properties: Id, Name and City.
package main
import (
"database/sql"
"log"
"net/http"
"text/template"
_ "github.com/go-sql-driver/mysql"
)
type Employee struct {
Id int
Name string
City string
}
func dbConn() (db *sql.DB) {
dbDriver := "mysql"
dbUser := "root"
dbPass := "root"
dbName := "goblog"
db, err := sql.Open(dbDriver, dbUser+":"+dbPass+"@/"+dbName)
if err != nil {
panic(err.Error())
}
return db
}
var tmpl = template.Must(template.ParseGlob("form/*"))
func Index(w http.ResponseWriter, r *http.Request) {
db := dbConn()
selDB, err := db.Query("SELECT * FROM Employee ORDER BY id DESC")
if err != nil {
panic(err.Error())
}
emp := Employee{}
res := []Employee{}
for selDB.Next() {
var id int
var name, city string
err = selDB.Scan(&id, &name, &city)
if err != nil {
panic(err.Error())
}
emp.Id = id
emp.Name = name
emp.City = city
res = append(res, emp)
}
tmpl.ExecuteTemplate(w, "Index", res)
defer db.Close()
}
func Show(w http.ResponseWriter, r *http.Request) {
db := dbConn()
nId := r.URL.Query().Get("id")
selDB, err := db.Query("SELECT * FROM Employee WHERE id=?", nId)
if err != nil {
panic(err.Error())
}
emp := Employee{}
for selDB.Next() {
var id int
var name, city string
err = selDB.Scan(&id, &name, &city)
if err != nil {
panic(err.Error())
}
emp.Id = id
emp.Name = name
emp.City = city
}
tmpl.ExecuteTemplate(w, "Show", emp)
defer db.Close()
}
func New(w http.ResponseWriter, r *http.Request) {
tmpl.ExecuteTemplate(w, "New", nil)
}
func Edit(w http.ResponseWriter, r *http.Request) {
db := dbConn()
nId := r.URL.Query().Get("id")
selDB, err := db.Query("SELECT * FROM Employee WHERE id=?", nId)
if err != nil {
panic(err.Error())
}
emp := Employee{}
for selDB.Next() {
var id int
var name, city string
err = selDB.Scan(&id, &name, &city)
if err != nil {
panic(err.Error())
}
emp.Id = id
emp.Name = name
emp.City = city
}
tmpl.ExecuteTemplate(w, "Edit", emp)
defer db.Close()
}
func Insert(w http.ResponseWriter, r *http.Request) {
db := dbConn()
if r.Method == "POST" {
name := r.FormValue("name")
city := r.FormValue("city")
insForm, err := db.Prepare("INSERT INTO Employee(name, city) VALUES(?,?)")
if err != nil {
panic(err.Error())
}
insForm.Exec(name, city)
log.Println("INSERT: Name: " + name + " | City: " + city)
}
defer db.Close()
http.Redirect(w, r, "/", 301)
}
func Update(w http.ResponseWriter, r *http.Request) {
db := dbConn()
if r.Method == "POST" {
name := r.FormValue("name")
city := r.FormValue("city")
id := r.FormValue("uid")
insForm, err := db.Prepare("UPDATE Employee SET name=?, city=? WHERE id=?")
if err != nil {
panic(err.Error())
}
insForm.Exec(name, city, id)
log.Println("UPDATE: Name: " + name + " | City: " + city)
}
defer db.Close()
http.Redirect(w, r, "/", 301)
}
func Delete(w http.ResponseWriter, r *http.Request) {
db := dbConn()
emp := r.URL.Query().Get("id")
delForm, err := db.Prepare("DELETE FROM Employee WHERE id=?")
if err != nil {
panic(err.Error())
}
delForm.Exec(emp)
log.Println("DELETE")
defer db.Close()
http.Redirect(w, r, "/", 301)
}
func main() {
log.Println("Server started on: http://localhost:8080")
http.HandleFunc("/", Index)
http.HandleFunc("/show", Show)
http.HandleFunc("/new", New)
http.HandleFunc("/edit", Edit)
http.HandleFunc("/insert", Insert)
http.HandleFunc("/update", Update)
http.HandleFunc("/delete", Delete)
http.ListenAndServe(":8080", nil)
}
Step 4: Creating Template files
Now it's time to build the Template files of our CRUD application. Create form folder at same location where we have created main.go.
a)Let's create a file named Index.tmpl inside the form folder and put the following code inside it.
{{ define "Index" }}
{{ template "Header" }}
{{ template "Menu" }}
IDNameCityViewEditDelete
{{ range . }}
{{ .Id }} {{ .Name }} {{ .City }} View Edit Delete{{ end }}
{{ template "Footer" }}
{{ end }}
b)Now create another file named Header.tmpl inside the same form folder and put the following code inside it.
{{ define "Header" }}
Golang Mysql Curd Example{{ end }}
c)Now create another file named Footer.tmpl inside the same form folder and put the following code inside it.
{{ define "Footer" }}
{{ end }}
d)Now create another file named Menu.tmpl inside the same form folder and put the following code inside it.
{{ define "Menu" }}
HOME |
{{ end }}
e)Next, we have to create Show.tmpl file for item details page, so again create this file in form folder.
{{ define "Show" }}
{{ template "Header" }}
{{ template "Menu" }}
Name: {{ .Name }}
City: {{ .City }}
Edit{{ template "Footer" }}
{{ end }}
f)Now we create new blade file for create new item, it's call New.tmpl file inside form.
{{ define "New" }}
{{ template "Header" }}
{{ template "Menu" }}
Name
City
{{ template "Footer" }}
{{ end }}
g)At last, we need to create Edit.tmpl file for update item, so again create this file in form folder.
{{ define "Edit" }}
{{ template "Header" }}
{{ template "Menu" }}
Name
City
{{ template "Footer" }}
{{ end }}
After a long journey finally we've created all files of our CRUD application with Golang and MySQL.
Run the following command
go run main.go
Load the following URL
http://localhost:8080/
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!