简体   繁体   English

如何在golang中使用GORM在数据库之间切换?

[英]How to switch between databases using GORM in golang?

I'm new to GORM in golang.我是 golang 的 GORM 新手。 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)一般我们select数据库是这样的: 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.但我的问题是我会在请求中得到“db_name”,这意味着我不知道可能会出现哪个 db_name,我必须根据该 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.所以现在,我将在 init function 中创建数据库指针,如下所示: DBGorm, err = gorm.Open("mysql", user:password@tcp(host:port)/)没有 db_name。

Now how will I switch to db_name coming to me in request.现在我将如何切换到 db_name 来请求我。 Because when I try to do DBGorm.Create(&con) , it shows No database selected .因为当我尝试做DBGorm.Create(&con)时,它显示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.如果我使用'database/sql',那么我可以像这样进行原始查询:“SELECT * FROM db_name.table_name”,这可以解决我的问题。 But how to do this in gorm?但是如何在gorm中做到这一点?

You can explicitly specify db_name and table_name using .Table() when doing query or other operation on table.在对表进行查询或其他操作时,您可以使用.Table()显式指定db_nametable_name

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

I saw a related article on Github.我在Github上看到了相关文章。 https://github.com/go-sql-driver/mysql/issues/173#issuecomment-427721651 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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