5

Golang gorm 怎么跨库查询 MySQL?

 2 years ago
source link: https://www.v2ex.com/t/842781
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  程序员

Golang gorm 怎么跨库查询 MySQL?

  gejigeji · 1 天前 · 1096 次点击

有大佬知道吗?

17 条回复    2022-03-25 20:28:29 +08:00

Cheivin

Cheivin      1 天前

select * from `databaseName`.`tableName`

xiancai

xiancai      1 天前

1. 使用 root 账号,拥有多个库的权限,按照 1 楼的方法进行查询
2. 建立多个连接,每个连接对应指定的库(为什么:为了安全,每个库都应该有单独的账号密码)
3. 不要跨库

Cheivin

Cheivin      1 天前

@gejigeji
func (Example) TableName() string {
return "databaseName.tableName"
}

gejigeji

gejigeji      1 天前

@xiancai 这些我知道, 但是在 Golang gorm 种怎么操作呢

gejigeji

gejigeji      1 天前

@Cheivin 连接呢, 不是必须要指定 DbName 吗?

imherer

imherer      1 天前

db 应该不多吧? 直接按 db 初始化多个 db 对象呢?

Cheivin

Cheivin      1 天前   ❤️ 1

1. 连接数据库的时候,你可以不指定默认的 DbName
dsn := "user:pass@tcp(127.0.0.1:3306)/?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})

2. 在声明模型的时候,通过 TableName() string 指定模型的数据库和表名
3. 或者查询的时候,通过 db.Table("databaseName.tableName") 指定指定库的表

lasuar

lasuar      23 小时 58 分钟前   ❤️ 1

db.table("T1 alias_t1").leftjoin("T2 alias_t2")... 或者 直接 db.raw/exec("原生 sql 该怎么写就怎么写")

gejigeji

gejigeji      23 小时 39 分钟前

@xiancai 你没答到点子上啊,8 楼才说得很明白, 不过还是谢谢你

gejigeji

gejigeji      23 小时 37 分钟前

@Cheivin 是的,多谢

gejigeji

gejigeji      23 小时 19 分钟前

@lasuar 是这样的,多谢

superfatboy

superfatboy      21 小时 25 分钟前

多看文档,能初始化多个实例

gejigeji

gejigeji      20 小时 21 分钟前

@yufpga 多谢, 是我没有好好看文档

jessun1990

jessun1990      14 小时 11 分钟前

啊,我这里也没有看到那个文档。

我的做法是在每次查询前面加一个 "use xxxx;"

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK