数据库操作
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

70 lines
1.2 KiB

package dbquery
import (
"database/sql"
"errors"
"fmt"
"strconv"
"log"
"time"
_ "github.com/denisenkom/go-mssqldb"
)
var MSDB_CONN *sql.DB
func MSConnect(DBHOST, DBUSER, DBPWD, DBNAME, DBPORT, encrypt string, conns ...int) error {
log.Println("msdb connectting...")
var dbConnErr error
if DBHOST != "" && DBUSER != "" && DBPWD != "" && DBPORT != "" { //&& DBNAME != ""
for i := 0; i < 10; i++ {
//连接字符串
db_port, _ := strconv.Atoi(DBPORT)
params := "server=%s;port=%d;database=%s;user id=%s;password=%s"
if encrypt != "" {
params = params + ";encrypt=" + encrypt
}
connString := fmt.Sprintf(params, DBHOST, db_port, DBNAME, DBUSER, DBPWD)
log.Println(connString)
//建立连接
MSDB_CONN, dbConnErr = sql.Open("mssql", connString)
if dbConnErr != nil {
log.Println("ERROR", "can not connect to Database, ", dbConnErr)
time.Sleep(time.Second * 5)
} else {
err = MSDB_CONN.Ping()
log.Println("msdb connected", err)
break
}
}
} else {
return errors.New("msdb connection params errors")
}
return dbConnErr
}
func CloseMSConn() error {
if MSDB_CONN != nil {
return MSDB_CONN.Close()
}
return nil
}