一、Gin框架 mysql配置
这里选择yaml文件配置
二、配置读取 viper
读取yaml文件中对应配置
三、mysql 的协程客户端
文件位置
package databaseimport ("database/sql""fmt""github.com/spf13/viper""log""net/http""sync""github.com/gin-gonic/gin"_ "github.com/go-sql-driver/mysql"
)var Db *sql.DB
var once sync.Oncefunc initDB() {var err errorDBUser := viper.GetString("database.username")DBPwd := viper.GetString("database.password")DBHost := viper.GetString("database.host")DBPort := viper.GetString("database.port")DBName := viper.GetString("database.name")//"username:password@tcp(127.0.0.1:3306)/dbname"dsn := DBUser + ":" + DBPwd + "@tcp(" + DBHost + ":" + DBPort + ")/" + DBNameDb, err = sql.Open("mysql", dsn)if err != nil {log.Fatal(err)}// 设置连接池参数(可选)Db.SetMaxOpenConns(10)Db.SetMaxIdleConns(5)// 验证连接是否有效if err = Db.Ping(); err != nil {log.Fatal(err)}
}func queryDB(wg *sync.WaitGroup, id int) {defer wg.Done()var name stringerr := Db.QueryRow("SELECT name FROM crm_user WHERE id=?", id).Scan(&name)if err != nil {log.Printf("Error querying database for id %d: %v", id, err)return}fmt.Printf("Queried name for id %d: %s\n", id, name)
}
这样就完成了,访问情况如下