请教大神们,go语言类似Java中的shardingJDBC的第三方组件
##### 项目需要单库分表,没有找到相关的组件,自己写了一个简易实现,使用xorm原生sql的支持实现单库分表
##### 1.先定义一个结构体字段与表结构字段对应
```
type User struct {
ID int64
Name string
Age int64
}
```
##### 2.通过对id取模获取对应的表名称
```
func getTableNameById(id int64) string {
switch id % 10 {
case 0:
return "user0"
case 1:
return "user1"
case 2:
return "user2"
case 3:
return "user3"
case 4:
return "user4"
case 5:
return "user5"
case 6:
return "user6"
case 7:
return "user7"
case 8:
return "user8"
case 9:
return "user9"
default:
return ""
}
}
```
##### 3.实现增删改查
```
func InsertUser(id int64, name string, age int64) error {
tbName := getTableNameById(id)
fmt.Println(tbName)
sql := "insert into " + tbName + "(i_d,name,age) values (?,?,?)"
_, err := x.Exec(sql, id, name, age)
if err != nil {
return err
}
return nil
}
func UpdateUserById(id int64, name string, age int64) error {
tbName := getTableNameById(id)
sql := "update " + tbName + " set name=?, age=? where i_d=? "
_, err := x.Exec(sql, name, age, id)
return err
}
func DeleteUserById(id int64) error {
tbName := getTableNameById(id)
sql := "delete from " + tbName + " where i_d = ?"
_, err := x.Exec(sql, id)
return err
}
func GetUserById(id int64) (*User, error) {
user := new(User)
tbName := getTableNameById(id)
sql := "select * from " + tbName + " where i_d = ?"
fmt.Println(sql)
results, err := x.SQL(sql, id).Get(user)
// results, err := x.QueryString(sql, id)
if err != nil {
return user, err
}
fmt.Println(results)
return user, nil
}
func GetAllUser() ([]User, error) {
var users []User
var i int64 = 0
for ; i < 10; i++ {
var tmp []User
tbName := getTableNameById(i)
sql := "select * from " + tbName
err := x.SQL(sql).Find(&tmp)
if err != nil {
return nil, err
}
users = append(users, tmp...)
// InsertUser(i, "name"+strconv.FormatInt(i, 10), i)
}
return users, nil
}
```
#5
更多评论
<a href="/user/focusonline" title="@focusonline">@focusonline</a> 可以实现数据库分表的功能
#2