-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
49 lines (43 loc) · 1.01 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package main
import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
"log"
"mybatis-gorm/utils"
"time"
)
type User struct {
ID uint `gorm:"primaryKey"`
Name string `gorm:"not null"`
Email string `gorm:"unique;not null"`
CreatedAt time.Time
UpdatedAt time.Time
}
func initDB() *gorm.DB {
dsn := "root:123584679y@tcp(47.100.102.21:3306)/gorm_sql?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatalf("failed to connect database: %v", err)
}
// 自动迁移模式
err = db.AutoMigrate(&User{})
if err != nil {
return nil
}
return db
}
func main() {
db := initDB()
// 测试数据
sql := `select * from users where email like #{email} and name like "王%" order by created_at limit #{pageSize}`
values := map[string]interface{}{
"email": "%qq.com",
"pageSize": 2,
}
var users []User
utils.TranSql(db, sql, values).Scan(&users)
// 打印返回值
for _, user := range users {
log.Printf("User: %+v", user)
}
}