update
This commit is contained in:
70
internal/db/mysql.go
Normal file
70
internal/db/mysql.go
Normal file
@@ -0,0 +1,70 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
message "m2pool-payment/internal/msg"
|
||||
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
)
|
||||
|
||||
type MySQLPool struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
// NewMySQLPool 初始化连接池
|
||||
func NewMySQLPool(cfg message.MysqlConfig) (*MySQLPool, error) {
|
||||
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
|
||||
cfg.User, cfg.Password, cfg.Host, cfg.Port, cfg.Database)
|
||||
db, err := sql.Open("mysql", dsn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 设置连接池参数
|
||||
db.SetMaxOpenConns(cfg.MaxOpenConns)
|
||||
db.SetMaxIdleConns(cfg.MaxIdleConns)
|
||||
db.SetConnMaxLifetime(cfg.ConnMaxLife)
|
||||
|
||||
// 测试连接
|
||||
if err := db.Ping(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &MySQLPool{db: db}, nil
|
||||
}
|
||||
|
||||
// Exec 执行 INSERT/UPDATE/DELETE
|
||||
func (p *MySQLPool) Exec(query string, args ...any) (sql.Result, error) {
|
||||
return p.db.Exec(query, args...)
|
||||
}
|
||||
|
||||
// Query 查询多行
|
||||
func (p *MySQLPool) Query(query string, args ...any) (*sql.Rows, error) {
|
||||
return p.db.Query(query, args...)
|
||||
}
|
||||
|
||||
// QueryRow 查询单行
|
||||
func (p *MySQLPool) QueryRow(query string, args ...any) *sql.Row {
|
||||
return p.db.QueryRow(query, args...)
|
||||
}
|
||||
|
||||
// Transaction 执行事务
|
||||
func (p *MySQLPool) Transaction(fn func(tx *sql.Tx) error) error {
|
||||
tx, err := p.db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := fn(tx); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// Close 关闭连接池
|
||||
func (p *MySQLPool) Close() error {
|
||||
return p.db.Close()
|
||||
}
|
||||
Reference in New Issue
Block a user