我正在尝试通过 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{})
- 1 回答
- 0 关注
- 450 浏览
添加回答
举报
0/150
提交
取消
