Files
monitor/backend/internal/db/factory.go
2025-12-02 23:20:10 +08:00

50 lines
1.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package db
import (
"context"
"database/sql"
"log"
)
// NewDB 根据配置创建数据库连接实例
func NewDB(cfg Config) (DB, error) {
// 只支持MySQL数据库
return NewMySQLDB(cfg)
}
// 基础数据库连接结构体
type baseDB struct {
db *sql.DB
}
// GetDB 获取原始数据库连接
func (b *baseDB) GetDB() *sql.DB {
return b.db
}
// Query 执行查询,返回多行结果
func (b *baseDB) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) {
return b.db.QueryContext(ctx, query, args...)
}
// QueryRow 执行查询,返回单行结果
func (b *baseDB) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row {
return b.db.QueryRowContext(ctx, query, args...)
}
// Exec 执行更新操作INSERT、UPDATE、DELETE
func (b *baseDB) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error) {
return b.db.ExecContext(ctx, query, args...)
}
// BeginTx 开始事务
func (b *baseDB) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error) {
return b.db.BeginTx(ctx, opts)
}
// Close 关闭数据库连接
func (b *baseDB) Close() error {
log.Println("Closing database connection")
return b.db.Close()
}