openwrt golang mysql_Example of Golang CRUD using MySQL from scratch - Go语言中文社区

openwrt golang mysql_Example of Golang CRUD using MySQL from scratch


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" }}

Registered

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

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 |

NEW

{{ 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" }}

Register {{ .Id }}

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" }}

New Name and City

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" }}

Edit Name and City

Name

City

{{ template "Footer" }}

{{ end }}

After a long journey finally we've created all files of our CRUD application with Golang and MySQL.

e6832f2100ebae8c33ef55d2e1c8021f.png

83b3596c00788106b5c5e421da67592a.png

Run the following command

go run main.go

Load the following URL

http://localhost:8080/

45ea4a8bd172565f938f23192e9cbcfb.png

025f00bce94d03c4aa433f0205fc8f6c.png

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_35460054/article/details/114354236
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-06-14 05:03:44
  • 阅读 ( 772 )
  • 分类:数据库

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢