如何提供MSSQL连接?它说它总是与代码联系在一起。即使信息不正确,也不会出错。
package main
import (
"database/sql"
"fmt"
_ "github.com/denisenkom/go-mssqldb"
"log"
)
var server = "DESKTOP\\SQLEXPRESS"
var port = 1433
var user = "loginx"
var password = "1"
var database = "test"
var db *sql.DB
func main() {
var err error
connString := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d;database=%s;",
server, user, password, port, database)
fmt.Println(server, user, password, database)
conn, err := sql.Open("mssql", connString)
if err != nil {
log.Fatal("Open connection failed:", err.Error())
}
fmt.Printf("Connected!\n")
defer conn.Close()
}
最佳答案
Open()中的mssql
应该是sqlserver
尝试更改此。db, err = sql.Open("sqlserver", connString)
所以您的main()看起来像..
var db *sql.DB
func main() {
var err error
// Create connection string
connString := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d",
server, user, password, port)
// Create connection pool
db, err = sql.Open("sqlserver", connString)
if err != nil {
log.Fatal("Error creating connection pool: " + err.Error())
}
log.Printf("Connected!\n")
// Close the database connection pool after program executes
defer db.Close()
}
关于sql-server - 进行MSSQL连接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56411705/