package svc import ( "app-cloudep-trade-service/internal/config" "database/sql" "fmt" "github.com/zeromicro/go-zero/core/logx" ) func mustDSN(c config.Config) string { // 構建 DSN 字符串 return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?parseTime=true&interpolateParams=%t", c.DB.User, c.DB.Password, c.DB.Host, c.DB.Port, c.DB.Database, c.DB.InterpolateParams, ) } func newDatabase(c config.Config) (*sql.DB, error) { // 創建基礎的 *sql.DB 連接 db, err := sql.Open("mysql", mustDSN(c)) if err != nil { logx.Error(fmt.Errorf("failed to connect to database: %w", err)) return nil, err } // 設置數據庫連接池參數 db.SetMaxIdleConns(c.DB.MaxIdleConns) db.SetMaxOpenConns(c.DB.MaxOpenConns) db.SetConnMaxLifetime(c.DB.ConnMaxLifetime) return db, nil }