mssql连接字符串格式:
server=127.0.0.1;user id=SA;password=Pwd123456;port=1433;database=master;encrypt=disable
mssql连接方法:
DB, err := gorm.Open(sqlserver.Open(c.Database.Source), &gorm.Config{
Logger: logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
logger.Config{
SlowThreshold: time.Second, // 慢 SQL 阈值
LogLevel: logger.Info, // Log level
Colorful: true, // 禁用彩色打印
},
), //常常使用gorm默认日志 并设置日志级别
})
if err != nil {
fmt.Println("err:", err)
return nil, err
}
也可以用另一个驱动包连接mssql:
import (
"gorm.io/driver/sqlserver"
"gorm.io/gorm"
)
// github.com/denisenkom/go-mssqldb
dsn := "sqlserver://gorm:LoremIpsum86@localhost:9930?database=gorm"
db, err := gorm.Open(sqlserver.Open(dsn), &gorm.Config{})
如果连接还是报错的话,可能是连接的dsn里没有加上 encrypt=disable
driver := viper.GetString("Database.Driver")
host := viper.GetString("Database.Host")
port := viper.GetString("Database.Port")
database := viper.GetString("Database.Database")
username := viper.GetString("Database.Username")
password := viper.GetString("Database.Password")
query := url.Values{}
query.Add("database", database)
query.Add("encrypt", "disable")
dsn := &url.URL{
Scheme: driver,
User: url.UserPassword(username, password),
Host: host + ":" + port,
RawQuery: query.Encode(),
}
fmt.Println(dsn.String())
db, err := gorm.Open(sqlserver.Open(dsn.String()), &gorm.Config{})
if err != nil {
panic("failed to connect database, err:" + err.Error())
}
如果对您有帮助,请帮点个赞,谢谢!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)