数据库操作
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.
 

65 lines
1.1 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 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)
connString := fmt.Sprintf("server=%s;port=%d;database=%s;user id=%s;password=%s", 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
}