mysql
This commit is contained in:
20
models/config.go
Normal file
20
models/config.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var Viper *viper.Viper
|
||||
|
||||
func init() {
|
||||
viper.SetConfigName("config") // 设置配置文件的名字
|
||||
viper.SetConfigType("yaml") // 设置配置文件的格式
|
||||
viper.AddConfigPath("./data") // 设置配置文件所在的路径
|
||||
if err := viper.ReadInConfig(); err != nil {
|
||||
log.Println("读取配置文件失败", err)
|
||||
panic(err)
|
||||
}
|
||||
Viper = viper.GetViper()
|
||||
}
|
44
models/mysql.go
Normal file
44
models/mysql.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"log"
|
||||
"strconv"
|
||||
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
)
|
||||
|
||||
func GetMysql() {
|
||||
viper := Viper // 从 models/config.go 中获取 viper 对象
|
||||
user := viper.Get("mysql.user").(string)
|
||||
password := viper.Get("mysql.password").(string)
|
||||
host := viper.Get("mysql.host").(string)
|
||||
port := viper.Get("mysql.port").(int)
|
||||
database := viper.Get("mysql.database").(string)
|
||||
sqlconf := user + ":" + password + "@tcp(" + host + ":" + strconv.Itoa(port) + ")/" + database + "?charset=utf8mb4&parseTime=True&loc=Local"
|
||||
|
||||
// 连接数据库
|
||||
db, err := sql.Open("mysql", sqlconf)
|
||||
if err != nil {
|
||||
log.Println("连接数据库失败", err)
|
||||
return
|
||||
}
|
||||
|
||||
// 从 web_images 表读取图片 id, version, width, height, format
|
||||
rows, err := db.Query("SELECT id, width, height, content FROM web_images WHERE id = 8888")
|
||||
if err != nil {
|
||||
log.Println("查询数据库失败", err)
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
// 遍历查询结果
|
||||
for rows.Next() {
|
||||
var id, width, height, content string
|
||||
if err = rows.Scan(&id, &width, &height, &content); err != nil {
|
||||
log.Println("读取数据库失败", err)
|
||||
return
|
||||
}
|
||||
log.Println(id, width, height, content)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user