q5/mysql.go
aozhiwei a0122ba8e5 1
2024-06-28 14:46:30 +08:00

78 lines
1.7 KiB
Go

package q5
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
type Mysql struct {
host string
port int32
user string
passwd string
database string
db *sql.DB
maxOpenConns int32
maxIdleConns int32
}
func (this *Mysql) init(host string, port int32, user string, passwd string, database string,
maxOpenConns int32, maxIdleConns int32) {
this.host = host
this.port = port
this.user = user
this.passwd = passwd
this.database = database
this.maxOpenConns = maxOpenConns
this.maxIdleConns = maxIdleConns
}
func (this *Mysql) Open() error {
connStr := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8",
this.user,
this.passwd,
this.host,
this.port,
this.database)
db, err := sql.Open("mysql", connStr)
this.db = db
if err == nil {
this.db.SetMaxOpenConns(int(this.maxOpenConns))
this.db.SetMaxIdleConns(int(this.maxIdleConns))
}
return err
}
func (this *Mysql) Close() {
if this.db != nil {
this.db.Close()
}
}
func (this *Mysql) Ping() error {
return this.db.Ping()
}
func (this *Mysql) Query(query string, args ...interface{}) (*sql.Rows, error) {
rows, err := this.db.Query(query, args...)
return rows, err
}
/*
func (this *Mysql) QueryRow(query string, args ...interface{}) *sql.Row {
return this.db.QueryRow(query, args...)
}
*/
func (this *Mysql) Exec(query string, args ...interface{}) (sql.Result, error) {
result, err := this.db.Exec(query, args...)
return result, err
}
func NewMysql(host string, port int32, user string, passwd string, database string, maxOpenConns int32, maxIdleConns int32) *Mysql {
conn := new(Mysql)
conn.init(host, port, user, passwd, database, maxOpenConns, maxIdleConns)
return conn
}