q5/mysql.go
2023-10-25 15:46:41 +08:00

67 lines
1.3 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
}
func (this *Mysql) init(host string, port int32, user string, passwd string, database string) {
this.host = host
this.port = port
this.user = user
this.passwd = passwd
this.database = database
}
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
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) *Mysql {
conn := new(Mysql)
conn.init(host, port, user, passwd, database)
return conn
}