我正在嘗試通過 ssh 連接到數(shù)據(jù)庫,我正在使用database/sql包連接到數(shù)據(jù)庫,但我不明白如何實現(xiàn)database/sqlgorm jinzhu/gorm。有人可以告訴我如何實現(xiàn)它嗎?或者有什么方法可以通過使用 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條經(jīng)驗 獲得超13個贊
繼續(xù)執(zhí)行相同的步驟,但不要使用 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 關注
- 363 瀏覽
添加回答
舉報
0/150
提交
取消