package main import ( "encoding/csv" "fmt" "log" "os" "strconv" "time" "github.com/gocarina/gocsv" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" ) // 定义模型结构体 type Record struct { ID uint `gorm:"primary_key"` Timestamp int64 `gorm:"index"` Field1 string Field2 int Field3 float64 } func main() { // 连接到数据库 db, err := gorm.Open("mysql", "username:password@tcp(host:port)/database?charset=utf8mb4&parseTime=True&loc=Local") if err != nil { log.Fatal(err) } defer db.Close() // 自动迁移表结构 db.AutoMigrate(&Record{}) // 打开CSV文件 filePath := "path/to/your/csv/file.csv" // 替换为你的CSV文件路径 file, err := os.Open(filePath) if err != nil { log.Fatal(err) } defer file.Close() // 解析CSV文件 reader := csv.NewReader(file) records, err := reader.ReadAll() if err != nil { log.Fatal(err) } // 将数据存入数据库 for _, row := range records { field1 := row[0] field2, _ := strconv.Atoi(row[1]) field3, _ := strconv.ParseFloat(row[2], 64) record := Record{ Timestamp: time.Now().Unix(), // int64类型时间戳 Field1: field1, Field2: field2, Field3: field3, } db.Create(&record) } fmt.Println("Data saved to database successfully.") }