【发布时间】: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 好的,先生。我已经编辑了问题
-
我添加了一个答案,看看是否有帮助