Bootstrap

Java读取本地CSV文件,并保存到数据库

package com.example.excel;

import com.csvreader.CsvReader;
import com.example.bean.CsvData;
import com.google.common.collect.Lists;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class CoarseRegulation {

    // 定义连接数据库所需要的信息
    private static final String DB_URL = "jdbc:mysql://localhost:3306/shuanghuan";
    private static final String USER = "root";
    private static final String PASS = "1234";



    public static void main(String[] args){

        CsvData csvData =null;
        CsvReader r;
        // 获取 Excel 文件
        File excelFile = new File("E:/OneDriver/OneDrive/桌面/2023-09-011.csv");
        try {

// 获取连接数据库的对象
            Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);

            r = new CsvReader("E:/OneDriver/OneDrive/桌面/双环erp/2023-09-011.csv",',', Charset.forName("GBK"));

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sdf.setLenient(false); // 设置严格验证日期

            //读取表头
            boolean b = r.readHeaders();
            while(r.readRecord()){
                csvData = new CsvData();
                //注意,此处的数字是取得第几列,从0开始数
                csvData.setId(Integer.parseInt(r.get(1)));
                csvData.setBeforeUpdate(r.get(2));
                csvData.setLateUpdate(r.get(3));
                csvData.setResult(r.get(4));
                csvData.setUpdateTime(sdf.parse(r.get(5)));

                PreparedStatement pstmt = conn.prepareStatement(
                        "INSERT INTO coarse_regulation (id, beforeUpdate, laterUpdate, result, Update_time)" +
                                " VALUES (?, ?, ?, ?, ?)");
                pstmt.setInt(1, Integer.parseInt(r.get(1)));
                pstmt.setString(2, r.get(2));
                pstmt.setString(3, r.get(3));
                pstmt.setString(4, r.get(4));
                pstmt.setTimestamp(5, new Timestamp(sdf.parse(r.get(5)).getTime()));
                pstmt.executeUpdate();
            }
            r.close();
        } catch (IOException | ParseException | SQLException e) {
            e.printStackTrace();
        }

    }
}

;