GO使用MySql

1.导入包(在VSCode的终端执行)

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

注:这个你需要安装Git,并且在电脑的“系统环境变量的【Path】中”添加Git安装目录的bin路径

 

 

2.调用代码

package main

import (
    "database/sql"
    "fmt"

    _ "github.com/go-sql-driver/mysql"
)

func main() {
    dsn := "username:password@tcp(127.0.0.1:3306)/database?charset=utf8"
    db, err := sql.Open("mysql", dsn)
    if err != nil {
        fmt.Printf("数据库链接字符串格式,错误 %v\n!", err)
        return
    }
    err = db.Ping()
    if err != nil {
        fmt.Printf("数据库链接,错误 %v\n!", err)
        return
    }
    fmt.Println("数据库连接成功。")
}

注:这里上面的 import中 需要引用自己安装的mysql(_,下划线指的是只初始化不使用,不然一保存就自动没掉了)

 

 

 

参考:https://www.bilibili.com/video/BV1fz4y1m7Pm?p=132

https://blog.csdn.net/qq_24822271/article/details/104335891

https://blog.csdn.net/qq_36944770/article/details/78849927

https://www.cnblogs.com/kaichenkai/p/11140555.html

 

posted @ 2021-07-01 13:48  蜗牛的礼物  阅读(62)  评论(0编辑  收藏  举报