简体   繁体   中英

How to switch between databases using GORM in golang?

I'm new to GORM in golang. I'm stuck at a point. Generally we select the database like this: DBGorm, err = gorm.Open("mysql", user:password@tcp(host:port)/db_name)
But my problem is I'll get the 'db_name' in the request, which means I don't know which db_name might come and I'll have to query according to that db_name. So now, I'll create the database pointer in the init function like this: DBGorm, err = gorm.Open("mysql", user:password@tcp(host:port)/) which is without the db_name.

Now how will I switch to db_name coming to me in request. Because when I try to do DBGorm.Create(&con) , it shows No database selected .

If I use 'database/sql', then I can make raw queries like this: "SELECT * FROM db_name.table_name", this can solve my problem. But how to do this in gorm?

You can explicitly specify db_name and table_name using .Table() when doing query or other operation on table.

DBGorm.Table("db_name.table_name").Create(&con)

I saw a related article on Github. https://github.com/go-sql-driver/mysql/issues/173#issuecomment-427721651

All you need to do is

  1. start a transaction,
  2. set you database
  3. run your desired query.
  4. and switch back to your desired DB
  5. commit once you are done.

below is an example

tx := db.Begin() // start transaction
tx.Exec("use " + userDB) // switch to tenant db
tx.Exec("insert into ....") // do some work
tx.Exec("use `no-op-db`") // switch away from tenant db (there is no unuse, so I just use a dummy)
tx.Commit() // end transaction

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM