如何在 golang 中使用 gorm 通过 ssh 连接数据库?
How do I connect database via ssh using gorm in golang?
我正在尝试通过 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}
}
继续执行相同的步骤,但不要 sql.Open 使用
dsn := fmt.Sprintf("%s:%s@mysql+tcp(%s)/%s", dbUser, dbPass, dbHost, dbName)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
我正在尝试通过 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}
}
继续执行相同的步骤,但不要 sql.Open 使用
dsn := fmt.Sprintf("%s:%s@mysql+tcp(%s)/%s", dbUser, dbPass, dbHost, dbName)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})