You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go GORM连接SQL Server的Windows身份验证连接字符串配置方法

Go GORM连接SQL Server的Windows身份验证配置

要使用Windows身份验证连接SQL Server,你需要调整连接字符串(DSN),移除用户名/密码部分,添加Windows身份验证的专属参数。

修改后的连接字符串

原SQL Server身份验证的DSN:

"sqlserver://sa:12345678@localhost:1433?database=gorm"

替换为Windows身份验证的DSN,有两种等效写法:

  1. 使用Integrated Security=true:
"sqlserver://localhost:1433?database=gorm&Integrated Security=true"
  1. 使用Trusted_Connection=true:
"sqlserver://localhost:1433?database=gorm&Trusted_Connection=true"

修改后的完整示例代码

将原代码中的DSN替换为上述字符串即可,完整代码如下:

package postgres

import (
    "gorm.io/driver/sqlserver"
    "gorm.io/gorm"
)

type Product struct {
    gorm.Model
    Code  string
    Price uint
}

func Main() {
    // 使用Windows身份验证的DSN(二选一即可)
    dsn := "sqlserver://localhost:1433?database=gorm&Integrated Security=true"
    // dsn := "sqlserver://localhost:1433?database=gorm&Trusted_Connection=true"
    
    db, err := gorm.Open(sqlserver.Open(dsn), &gorm.Config{})
    if err != nil {
        panic("failed to connect database")
    }
    // 迁移数据库 schema
    db.AutoMigrate(&Product{})
    // 创建数据
    db.Create(&Product{Code: "D42", Price: 100})
    // 查询数据
    var product Product
    db.First(&product, 1)                 // 根据整数主键查找产品
    db.First(&product, "code = ?", "D42") // 根据编码D42查找产品
    // 更新数据 - 将产品价格改为200
    db.Model(&product).Update("Price", 200)
    // 更新数据 - 修改多个字段
    db.Model(&product).Updates(Product{Price: 200, Code: "F42"}) // 仅更新非零值字段
    db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"})
    // 删除数据 - 删除指定产品
    db.Delete(&product, 1)
}

注意事项

  • 确保运行该Go程序的Windows账号拥有目标SQL Server数据库的访问权限(比如登录权限、对应数据库的读写权限等)。
  • Integrated Security=true和Trusted_Connection=true是等效的,任选其一即可。

内容的提问来源于stack exchange,提问作者Đỗ Như Vỹ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 14:52:59