【问题标题】:How do I connect database via ssh using gorm in golang?如何在 golang 中使用 gorm 通过 ssh 连接数据库?
【发布时间】:2021-01-11 10:11:06
【问题描述】:

我正在尝试通过 ssh 连接到数据库,我正在使用 database/sql 包连接到数据库,但我不明白如何将 database/sql 实现到 gorm jinzhu/gorm。有人可以告诉我如何实现吗?或者有什么方法可以通过使用 gorm 包来连接? 我对 golang 还很陌生。

这就是代码的样子。 主要问题是在NewBrandsRepository 方法中不能使用类型*sql.DB 作为*gorm.DB

// Connect to the SSH Server
sshcon, 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 parameter
mysql.RegisterDial("mysql+tcp", (&ViaSSHDialer{sshcon}).Dial)

// And now we can use our new driver with the regular mysql connection string tunneled through the SSH connection
db, 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}
}

【问题讨论】:

  • 分享你的尝试;我们可以帮助填补空白
  • @ShubhamSrivastava 好的,先生。我已经编辑了问题
  • 我添加了一个答案,看看是否有帮助

标签: go go-gorm


【解决方案1】:

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

dsn := fmt.Sprintf("%s:%s@mysql+tcp(%s)/%s", dbUser, dbPass, dbHost, dbName)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})

【讨论】:

  • 一些更正,因为这给了我一个错误。谢谢你为我提供代码 tho dsn := fmt.Sprintf("%s:%s@mysql+tcp(%s:%s)/%s", dbUser, dbPass, dbHost, db.Port, dbName) db,错误 := gorm.Open(mysql.Open(dsn), &gorm.Config{})
  • @FajarS.Salviro 我似乎错过了那部分谢谢
猜你喜欢
  • 2019-07-13
  • 2019-02-12
  • 2017-04-25
  • 2020-10-15
  • 2016-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-06
相关资源
最近更新 更多