千恋*万花

  • 首页
  • 个人简历
  • 文章分类
    • 后端开发
    • 运维
    • 基础知识
    • 笔记
    • 工作运维记录
    • 随笔
    • 未分类文章
  • 管理
    • 后台管理
    • 登出
萌奈の笔记簿
分享我的努力,希望为你助力
  1. 首页
  2. 后端开发
  3. gin
  4. 正文

Gin框架中使用数据库——Go Gin框架(七)

2020-10-08 3757点热度 0人点赞 0条评论

安装MySQL数据库

MySQL官方链接:https://dev.mysql.com/downloads/mysql/
Debian:sudo apt install mysql-5.7
安装过程:略

Go 安装MySQL驱动

go get "github.com/go-sql-driver/mysql"

在项目中使用MySQL

在go mod模式下,还需要在项目中引用mysql模块

go.mod文件

module MonaGinWeb

go 1.15

require (
    github.com/gin-gonic/gin v1.6.3
    github.com/go-sql-driver/mysql v1.5.0
)

在go中连接MySQL

import (
    "database/sql"
    "log"
    "strconv"
)

var db *sql.DB

func init() {
    c := MySQLConnInfo{
        user:       "",
        password:   "",
        connMethod: "tcp",
        host:       "",
        port:       0,
        dbname:     "",
        otherArgs:  "",
    }
    //数据库连接字符串
    //"user:password@tcp(host:port)/dbname"
    connStr := c.user + ":" + c.password +
        "@" + c.connMethod + "(" + c.host + ":" + strconv.Itoa(c.port) + ")/" +
        c.dbname + c.otherArgs
    if temp, err := sql.Open("mysql", connStr); err == nil {
        db = temp
    } else { //连接出现错误
        log.Fatal(err.Error())
        return
    }
}
  • func Open(driverName string, dataSourceName string) (*DB, error):该函数用于打开程序与SQL数据库的连接。其会返回创建(连接成功)的一个DB指针,有两个参数:
    • driverName string:用于指定数据库引擎
    • dataSourceName string:用于传入数据库的连接字符串

MySQL的增删改查

(待补充)

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可
标签: Gin Gin框架 go Golang 心得 mysql 学习心得
最后更新:2022-10-27

初音萌奈

我是练习时长 一年半 的后端开发程序员 谢谢你参观我的博客! 本网站现已支持IPv6 ☞ 个人简历 ☜

点赞
< 上一篇
下一篇 >
文章目录
  • 安装MySQL数据库
  • Go 安装MySQL驱动
  • 在项目中使用MySQL
    • MySQL的增删改查

COPYRIGHT © 2023 HatsuneMona ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

晋ICP备17007130号-4