current position:Home>Go native development blog project series (the third)

Go native development blog project series (the third)

2022-08-06 17:29:33deer fish

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第9天,点击查看活动详情

The original video address of the project:www.bilibili.com/video/BV1VS…


连接数据库

Go 语言中的 database/sql 包提供了保证 sql class or class sql 数据库的泛用接口,并不提供具体的数据库驱动,使用 database/sql 包时必须注入(至少)A database driver.

go get -u github.com/go-sql-diver/mysql
复制代码

open 打开一个 diverName 指定的数据库,dataSourceName指定数据源,The general package includes at least the database file name and connection letter.

dsn := "user:[email protected](127.0.0.1:3306)/dbname"
复制代码

使用 go-sql-driver 来连接 mysql 数据库,The time zone obtained is by default UTC+0 的,It is different from the East Eight District where we are located,The stored value has8小时误差.

UTC 即世界标准时间,中国大陆、中国香港、中国澳门、中国台湾、蒙古国、新加坡、马来西亚、菲律宾、西澳大利亚州的时间与UTC的时差均为+8,也就是UTC+8.

mysql 连接的 dsn 中添加 parseTime=trueloc=Local,此处的 Local Can be changed to a specific time zone,We all use the Shanghai time zone (Asia/Shanghai),注意要用 url.QueryEscape Encode the time zone used before it can be used,dsn 写法如下:

db, err := sql.Open("mysql", "user:[email protected](127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai")
复制代码

e-book-website/databases/mysql.go

package databases

import (
   "database/sql"
   _ "github.com/go-sql-driver/mysql"
   "log"
   "time"
)

var DB *sql.DB

func init() {
   dsn := "root:[email protected](localhost:3306)/goblog?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai"
   db, err := sql.Open("mysql", dsn)
   if err != nil {
      log.Println("连接数据库异常")
      log.Println(err)
   }
   db.SetMaxIdleConns(5)
   db.SetMaxOpenConns(100)
   db.SetConnMaxLifetime(time.Minute * 3)
   db.SetConnMaxIdleTime(time.Minute * 1)
   err = db.Ping()
   if err != nil {
      log.Println("数据库无法连接")
      _ = db.Close()
      log.Println(err)
   }
   DB = db
}
复制代码

创建 blog_category 表

create database goblog;

use goblog;

create table `blog_category`(
  `cid` int not null auto_increment,
  `name` varchar(20) default null comment '名称',
  `create_at` timestamp default null comment '创建时间',
  `update_at` timestamp default null comment '更新时间',
  primary key(`cid`)
)engine=InnoDB auto_increment=1 default charset=utf8 comment='分类表';

insert into blog_category VALUES(1, 'React', '2022-07-03', '2022-07-04');
复制代码

e-book-website/views/index.go

service 目录,Process business layer data.

func (*HTMLApi) Index(w http.ResponseWriter, r *http.Request) {
   index := common.Template.Index

   homedata, err := service.GetAllIndexInfo()
   if err != nil {
      log.Println(err)
      index.WriteData(w, errors.New("系统错误,请联系管理员"))
   }
   index.WriteData(w, homedata)
}
复制代码

e-book-website/service/index.go

除了 categorys Connect using a database,Everything else we use

package service

import (
   "blog-go/config"
   "blog-go/databases"
   "blog-go/models"
)

func GetAllIndexInfo() (*models.HomeResponse, error) {
   categorys, err := databases.GetAllCategory()
   if err != nil {
      return nil, err
   }
   var posts = []models.PostMore{
      {
         Pid:          1,
         Title:        "go博客",
         Content:      "内容",
         UserName:     "码神",
         ViewCount:    123,
         CreateAt:     "2022-02-20",
         CategoryId:   1,
         CategoryName: "go",
         Type:         0,
      },
   }
   var data = &models.HomeResponse{
      config.Cfg.Viewer,
      categorys,
      posts,
      1,
      1,
      []int{1},
      true,
   }
   return data, nil
}
复制代码

e-book-website/databases/category.go

select * from blog_category 获取数据.Query 返回的结果集是sql.[Rows]类型.它有一个 Next 方法,A cursor that can iterate over the database,And then get the data of each row.

package databases

import (
   "blog-go/models"
   "log"
)

func GetAllCategory() ([]models.Category, error) {
   rows, err := DB.Query("select * from blog_category")
   if err != nil {
      log.Println("err", err)
      return nil, err
   }
   var categorys []models.Category
   for rows.Next() {
      var category models.Category
      err = rows.Scan(&category.Cid, &category.Name, &category.CreateAt, &category.UpdateAt)
      if err != nil {
         log.Println("err", err)
         return nil, err
      }
      categorys = append(categorys, category)
   }
   return categorys, nil
}
复制代码

重启项目,刷新页面.

图片.png

copyright notice
author[deer fish],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/218/202208061702145097.html

Random recommended