添加批量导入

This commit is contained in:
JACKYMYPERSON
2025-09-25 11:49:11 +08:00
parent 1d2fdf4882
commit 7339dd649e

View File

@@ -1,10 +1,85 @@
package test package test
import ( import (
"github.com/gin-gonic/gin" "encoding/json"
"net/http" "fmt"
"log"
"os"
"strings"
"time"
"toutoukan/init/databaseInit"
"gorm.io/gorm"
// 假设这是你的数据库连接包,你需要确保它能提供一个 *gorm.DB 实例
// "toutoukan/init/databaseInit"
) )
func Testjwt(c *gin.Context) { // 定义你的时间格式常量
c.JSON(http.StatusOK, gin.H{"code": 20002, "msg": "处理请求成功"}) const CustomTimeFormat = "2006-01-02 15:04:05"
// CustomTime 结构体用于处理非标准 JSON 时间格式
type CustomTime struct {
time.Time
}
// UnmarshalJSON 实现了 json.Unmarshaler 接口
func (ct *CustomTime) UnmarshalJSON(b []byte) (err error) {
s := strings.Trim(string(b), `"`) // 移除 JSON 字符串两端的引号
if s == "null" || s == "" {
ct.Time = time.Time{}
return nil
}
// 使用你的目标格式进行解析
ct.Time, err = time.Parse(CustomTimeFormat, s)
return
}
// UserInfo 结构体
type UserInfo struct {
UID string `json:"uid" gorm:"column:uid;primaryKey"`
Telephone string `json:"telephone" gorm:"column:telephone"`
Password string `json:"password" gorm:"column:password"`
AvatarURL string `json:"avatar_url" gorm:"column:avatar_url"`
Gender int `json:"gender" gorm:"column:gender"`
// 使用 CustomTime 类型来处理非标准时间格式
BirthdateDate CustomTime `json:"birthdate_date" gorm:"column:birthdate-date"`
CreatedTime CustomTime `json:"createdtime" gorm:"column:createdtime"`
UpdatedTime CustomTime `json:"updatedtime" gorm:"column:updatedtime"`
Bio string `json:"bio" gorm:"column:bio"`
Username string `json:"username" gorm:"column:username"`
TotalPoints int `json:"total_points" gorm:"column:total_points"`
}
// TableName 确保 GORM 使用正确的表名
func (UserInfo) TableName() string {
return "user_info"
}
// ImportUsersFromJSON 导入用户数据到数据库
func ImportUsersFromJSON(filePath string) {
// 1. 读取 JSON 文件
data, err := os.ReadFile(filePath)
if err != nil {
log.Fatalf("无法读取文件 %s: %v", filePath, err)
}
// 2. 解析 JSON 数据
var users []UserInfo
if err := json.Unmarshal(data, &users); err != nil {
log.Fatalf("JSON 解析失败 (请检查 JSON 结构和时间格式是否正确): %v", err)
}
// 3. 批量插入到数据库
// 插入时跳过默认事务,并使用批量插入优化性能
result := databaseInit.UserDB.Session(&gorm.Session{SkipDefaultTransaction: true}).
CreateInBatches(&users, 100)
if result.Error != nil {
log.Fatalf("批量插入失败: %v", result.Error)
}
fmt.Printf("成功导入 %d 条用户数据到 user_info 表。\n", result.RowsAffected)
} }