为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 golang 中使用 gorm 通过 ssh 连接数据库?

如何在 golang 中使用 gorm 通过 ssh 连接数据库?

Go
翻翻过去那场雪 2022-07-04 10:37:21
我正在尝试通过 ssh 连接到数据库,我正在使用database/sql包连接到数据库,但我不明白如何实现database/sqlgorm jinzhu/gorm。有人可以告诉我如何实现它吗?或者有什么方法可以通过使用 gorm 包来连接?我对golang还很陌生。这就是代码的样子。主要问题是NewBrandsRepository方法不能使用类型*sql.DB作为*gorm.DB// Connect to the SSH Serversshcon, errSSH := ssh.Dial("tcp", fmt.Sprintf("%s:%d", sshHost, sshPort), sshConfig)if errSSH != nil {}defer sshcon.Close()// Now we register the ViaSSHDialer with the ssh connection as a parametermysql.RegisterDial("mysql+tcp", (&ViaSSHDialer{sshcon}).Dial)// And now we can use our new driver with the regular mysql connection string tunneled through the SSH connectiondb, errDB := sql.Open("mysql", fmt.Sprintf("%s:%s@mysql+tcp(%s)/%s", dbUser, dbPass, dbHost, dbName))if errDB != nil {    fmt.Printf("Failed to connect to the db: %s\n", errDB.Error())}fmt.Printf("Successfully connected to the db\n")test := NewBrandsRepository(db)NewBrandsRepository方法是这样的type brandsRepositoryImpl struct {    db *gorm.DB}func NewBrandsRepository(db *gorm.DB) *brandsRepositoryImpl {    return &brandsRepositoryImpl{db}}
查看完整描述

1 回答

?
慕桂英4014372

TA贡献1871条经验 获得超13个赞

继续执行相同的步骤,但不要使用 sql.Open 使用


dsn := fmt.Sprintf("%s:%s@mysql+tcp(%s)/%s", dbUser, dbPass, dbHost, dbName)

db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})


查看完整回答
反对 回复 2022-07-04
  • 1 回答
  • 0 关注
  • 451 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号