当前位置:网站首页>Go novice exploration road 1

Go novice exploration road 1

2022-06-25 12:36:00 Velly_ zheng

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 :

  1. Log module
  2. Middle key
  3. Parameter configuration
  4. database ORM Model
  5. Return to format
  6. swagger file
  7. unit testing

Prioritize implementation functions

  1. Connect to the database and write data to it
  2. database ORM Model
  3. 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 :
 Insert picture description here

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 :
 Insert picture description here

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 ?
 Insert picture description here

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 ~~

原网站

版权声明
本文为[Velly_ zheng]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202200529183917.html