当前位置:网站首页>Go novice exploration road 1
Go novice exploration road 1
2022-06-25 12:36:00 【Velly_ zheng】
go Novice exploration road 1
install go
Of course , A new language , The first step is to install the configuration environment on your own computer , send go The project can run in your own computer . Here we search by ourselves , There are many resources on the Internet .
Set a small goal
My goal is to use it quickly go Development , All the other things you need to know will be learned by yourself if you encounter problems in the development process , Follow up supplementary theory ~~~ I set myself a small goal , Use go Write back end API, Save form submission data :
Big goals in the later stage
Use excel download or Upload millions of data , Custom download format or Upload format
Small target design
Need to implement the function :
- Log module
- Middle key
- Parameter configuration
- database ORM Model
- Return to format
- swagger file
- unit testing
Prioritize implementation functions
- Connect to the database and write data to it
- database ORM Model
- Back end API
1. Connect to database
main.go
package main
import (
beego "github.com/astaxie/beego/server/web"
mysql "ExcelHandleProject/bootstrap"
)
func main() {
db := mysql.ConnectDb()
mysql.CreateNewTable(db)
mysql.InsertData(db)
mysql.QueryData(db)
mysql.QueryAllData(db)
mysql.DeleteData(db)
beego.Run()
}
mysql.go
file location :
package bootstrap
import (
"fmt"
"log"
"time"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
func ConnectDb() *sql.DB {
db, err := sql.Open("mysql", "root:[email protected](127.0.0.1:3306)/excel_handle_project?parseTime=true")
if err != nil {
log.Fatal(err)
}
if err := db.Ping(); err != nil {
log.Fatal(err)
}
fmt.Println("connect mysql success!")
return db
}
func CreateNewTable(db *sql.DB) {
query := ` CREATE TABLE users ( id INT AUTO_INCREMENT, username TEXT NOT NULL, password TEXT NOT NULL, created_at DATETIME, PRIMARY KEY (id) );`
if _, err := db.Exec(query); err != nil {
log.Fatal(err)
}
fmt.Println("create table success!")
}
func InsertData(db *sql.DB) {
username := "johndoe"
password := "secret"
createdAt := time.Now()
result, err := db.Exec(`INSERT INTO users (username, password, created_at) VALUES (?, ?, ?)`, username, password, createdAt)
if err != nil {
log.Fatal(err)
}
id, err := result.LastInsertId()
_ = fmt.Sprintf("insert new data success, and id is %d", id)
}
func QueryData(db *sql.DB) {
var (
id int
username string
password string
createdAt time.Time
)
query := "SELECT id, username, password, created_at FROM users WHERE id = ?"
if err := db.QueryRow(query, 1).Scan(&id, &username, &password, &createdAt); err != nil {
log.Fatal(err)
}
fmt.Println(id, username, password, createdAt)
}
func QueryAllData(db *sql.DB) {
type user struct {
id int
username string
password string
createdAt time.Time
}
rows, err := db.Query(`SELECT id, username, password, created_at FROM users`)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var users []user
for rows.Next(){
var u user
err := rows.Scan(&u.id, &u.username, &u.password, &u.createdAt)
if err != nil {
log.Fatal(err)
}
users = append(users, u)
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
fmt.Printf("%#v", users)
}
func DeleteData(db *sql.DB) {
_, err := db.Exec(`DELETE FROM users WHERE id = ?`, 1)
if err != nil {
log.Fatal(err)
}
fmt.Printf("delele data success!")
}
Running results :
2. if bootstrap There are multiple files under the folder
Novices are prone to file calling problems , The above example bootstrap There is only one... Under the file go file , Default package by bootstrap
If bootstrap How to do if there are multiple files ?
If in bootstrap There are no other folders under , Only multiple files , Of these multiple files package It has to be the same , And of these documents function The name of cannot be duplicate ; This package The name of can be folder name , You can also customize the same name
If you want to be clear go File functionality , You can create another folder under the folder , then mysql.go Move in , here ,mysql.go Of package The name is mysql
import Remember one principle when you , Specific to package name , Not the file name , Nor is it a folder name
Changing main.go file
import (
beego "github.com/astaxie/beego/server/web"
"ExcelHandleProject/bootstrap/mysql"
)
func main() {
db := mysql.ConnectDb()
mysql.CreateNewTable(db)
mysql.InsertData(db)
mysql.QueryData(db)
mysql.QueryAllData(db)
mysql.DeleteData(db)
beego.Run()
}
Summary
This section focuses on the local package reference , other mysql operation , As long as you are familiar with go grammar , There is no difficulty ~~
边栏推荐
- Wechat forbids sharing
- Dark horse shopping mall ---6 Brand, specification statistics, condition filtering, paging sorting, highlighting
- How do super rookies get started with data analysis?
- R language uses GLM function to build Poisson logarithmic linear regression model, processes three-dimensional contingency table data to build saturation model, and poisgof function of epidisplay pack
- Install MySQL client
- Qiantang Pingou source code -- Qiantang Pingou app system development source code sharing
- How can we make an annual income of onemillion yuan by making our own media video?
- An example of using dynamic datalist
- Is it safe to open an account and buy stocks on the Internet?
- Mpai data science platform SVM support vector machine classification \ explanation of regression parameter adjustment
猜你喜欢

The first techo day Tencent technology open day in 2022 will be held online on June 28

Today, I will explain to you what is DFI and its development prospects

Uncover gaussdb (for redis): comprehensive comparison of CODIS

Time series analysis - how to use unit root test (ADF) correctly?

A commonly used statistical modeling method -- difference analysis

MySQL common interview questions

Understanding and construction of devsecops and Devops

Jeecgboot startup popup configuration is still incorrect

laravel 9

ECSHOP commodity page multi-attribute batch purchase plug-ins ECSHOP wholesale plug-ins multi-attribute order placing, multi-attribute batch purchase of commodities
随机推荐
Ten commandments of self-learning in machine learning
What is principal component analysis? Dimension reduction of classical case analysis variables
Online blind box system development function introduction and some source code sharing
devsecops与devops的理解与建设
Yunfan mall -- Yunfan mall system development source code sharing
The first techo day Tencent technology open day in 2022 will be held online on June 28
JQ verifies whether the input color is legal
做自媒体视频需要怎么做才能年收入一百万?
An example of using dynamic datalist
Uncover gaussdb (for redis): comprehensive comparison of CODIS
Wait for the end of the network request in the uniapp Onshow method before executing the subsequent code content
Rank sum ratio comprehensive evaluation method for common models in mathematical modeling
How to use SPSS to do grey correlation analysis? Quick grasp of hand-to-hand Teaching
PHP numeric array sorting and associative array sorting
揭秘GaussDB(for Redis):全面對比Codis
一款好用的印章设计工具 --(可转为ofd文件)
Execution order of MySQL query statements join, on and where
Controllable character image synthesis based on attribute decomposition and Gan reproduction
Arm V7 continuous load / store
Thinkphp3 use phpword to modify the template and download it
