在使用GORM连接SQL Server数据库时,如果密码中包含特殊字符(如@
、:
、/
、?
、&
等),可能会导致连接字符串解析错误。为了避免这个问题,你可以对密码中的特殊字符进行URL编码(Percent-Encoding),然后将编码后的密码放入连接字符串中。
P@ssw0rd!
,编码后的结果可能是P%40ssw0rd%21
。@
编码为 %40
!
编码为 %21
修改连接字符串: 在GORM的连接字符串中,使用编码后的密码。例如:
dsn := "sqlserver://username:P%40ssw0rd%21@localhost:1433?database=yourdbname"
db, err := gorm.Open(sqlserver.Open(dsn), &gorm.Config{})
其中:
username
是你的数据库用户名。P%40ssw0rd%21
是编码后的密码。localhost:1433
是数据库服务器地址和端口。yourdbname
是你要连接的数据库名称。测试连接: 运行代码,确保能够成功连接到SQL Server数据库。
package main
import (
"gorm.io/driver/sqlserver"
"gorm.io/gorm"
)
func main() {
// 使用URL编码后的密码
dsn := "sqlserver://username:P%40ssw0rd%21@localhost:1433?database=yourdbname"
db, err := gorm.Open(sqlserver.Open(dsn), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
// 测试连接
var result int
db.Raw("SELECT 1").Scan(&result)
if result == 1 {
println("Connected to SQL Server successfully!")
}
}
%
字符,也需要进行编码(编码为%25
)。通过这种方式,你可以安全地在GORM连接字符串中使用包含特殊字符的密码。