gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:36:53 25 4
gpt4 key购买 nike

在我的用例中,每个用户都有一个数据库(我知道这不是最好的决定,而是项目要求)。我想打开一个连接并为每个查询更改数据库名称。

我可以使用 db.Exec("use clientdatabase;");在执行每个查询之前更改数据库,但如果同时另一个查询到达或正在执行可能会出现问题,因为所有应用程序都使用相同的数据库连接。

也许,我可以使用每个客户端/数据库的连接映射,其中最大元素数为映射并删除旧连接。

即使我可以为每个查询创建一个连接,但如果一个客户端有多个查询,这可能会浪费时间。

最佳答案

我找到了重用具有不同数据库名称的相同连接的方法。我的解决方案是使用事务并在事务开始时设置数据库名称。以下带有输出的代码显示了一个示例:

//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()

之后输出:

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

如您所见,第一个和第三个输出对应于 t1 中日期为 2018-05-25 12:25:12 +0200 CEST 的“默认”数据库。而第二个对应于t2中的“seconddb”数据库。

关于mysql - 在 GORM 中,哪个是管理多个 mysql 数据库名称的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50754407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com