doumeng06063991 2018-06-08 06:13
浏览 3228

在GORM中,哪种方法是管理多个mysql数据库名称的最佳方法?

I have a database per user in my use case (I know it is not the best decision but is a project requirement). I would like to open one connection and change the database name for every query.

I could use db.Exec("use clientdatabase;"); to change the database before execute every query but if at the same time another query arrives or is executing could be problems because all the app are using the same db connection.

May be, I could use a map of connections per client/database with a map number of elements in the max and deleting old connections.

Even I could create a connection for every query, but it could be a waste of time if one client have several queries.

  • 写回答

1条回答 默认 最新

  • dpsx99068 2018-06-08 11:41
    关注

    I have found the way to reuse the same connection with different database names. My solution is to use transactions and set the database name when the transaction has begun. The following code with an output shows an example:

    //create transaction1 in nameDB = default
    tx1 := DB.Begin()
    var users1 []User
    tx1.Find(&users1)
    fmt.Println(users1[0].CreatedAt)
    
    //create new transaction and change nameDB to seconddb
    tx2 := DB.Begin()
    tx2.Exec("use seconddb;")
    var users2 []User
    tx2.Find(&users2)
    fmt.Println(users2[0].CreatedAt)
    //close tx2 so, it teakes effect on DB
    tx2.Commit()
    
    //same query with transaction1 to show that we are in default bd
    var users3 []User
    tx1.Find(&users3)
    fmt.Println(users3[0].CreatedAt)
    tx1.Commit()
    

    After that the output:

    2018-05-25 12:25:12 +0200 CEST
    2018-05-23 12:43:51 +0200 CEST
    2018-05-25 12:25:12 +0200 CEST
    

    As you can see, the first and the third outputs corresponds to "default" database with date 2018-05-25 12:25:12 +0200 CEST in t1. And the second corresponds to "seconddb" database in t2.

    评论

报告相同问题?

悬赏问题

  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?