| | |
| | | package com.se.simu.utils; |
| | | |
| | | import com.alibaba.fastjson.JSON; |
| | | import com.alibaba.fastjson.JSONArray; |
| | | import com.alibaba.fastjson.JSONObject; |
| | | import org.apache.commons.csv.CSVFormat; |
| | | import org.apache.commons.csv.CSVRecord; |
| | | |
| | |
| | | * @param stationRainFile Station Rain 文件 |
| | | * @param tableName 表名称 |
| | | */ |
| | | public static void readCsvSaveLocal(String stationRainFile, String tableName) { |
| | | public static JSONArray readCsvSaveLocal(String stationRainFile, String tableName) { |
| | | // 1. 创建SQLite数据库连接 |
| | | JSONArray array=null; |
| | | try (Connection conn = DriverManager.getConnection("jdbc:sqlite:rainfall.db")) { |
| | | if (conn != null) { |
| | | // 2. 创建表(如果不存在) |
| | |
| | | // 4. 开始事务 |
| | | conn.setAutoCommit(false); |
| | | // 5. 读取CSV文件并插入数据 |
| | | readCsvAndInsertDatas(stationRainFile, conn, tableName); |
| | | array = readCsvAndInsertDatas(stationRainFile, conn, tableName); |
| | | // 6. 提交事务 |
| | | conn.commit(); |
| | | System.out.println("数据成功插入到SQLite数据库!"); |
| | |
| | | } catch (SQLException e) { |
| | | System.err.println("SQLite连接失败: " + e.getMessage()); |
| | | } |
| | | return array; |
| | | } |
| | | |
| | | |
| | | private static void readCsvAndInsertDatas(String csvFilePath, Connection conn, String tableName) { |
| | | private static JSONArray readCsvAndInsertDatas(String csvFilePath, Connection conn, String tableName) { |
| | | // 使用 Apache Commons CSV 读取CSV文件 |
| | | JSONArray array = new JSONArray(); |
| | | try (Reader reader = new InputStreamReader(Files.newInputStream(Paths.get(csvFilePath)), "GBK")) { |
| | | Iterable<CSVRecord> records = CSVFormat.DEFAULT |
| | | .withHeader("雨量站", "降雨量", "经度", "纬度", "datatime") |
| | |
| | | .parse(reader); |
| | | |
| | | String insertDataSql = "INSERT INTO " + tableName + " (station_name, rainfall, longitude, latitude, datetime) VALUES (?, ?, ?, ?, ?);"; |
| | | |
| | | try (PreparedStatement pstmt = conn.prepareStatement(insertDataSql)) { |
| | | // 批量大小 |
| | | int batchSize = 1000; |
| | |
| | | pstmt.setDouble(3, longitude); |
| | | pstmt.setDouble(4, latitude); |
| | | pstmt.setString(5, datetime); |
| | | |
| | | JSONObject jsonObject = new JSONObject(); |
| | | jsonObject.put("stationName", stationName); |
| | | jsonObject.put("rainfall", rainfall); |
| | | jsonObject.put("longitude", longitude); |
| | | jsonObject.put("latitude", latitude); |
| | | jsonObject.put("datetime", datetime); |
| | | array.add(jsonObject); |
| | | // 添加到批处理 |
| | | pstmt.addBatch(); |
| | | count++; |
| | |
| | | } catch (IOException e) { |
| | | System.err.println("读取CSV或插入数据时出错: " + e.getMessage()); |
| | | } |
| | | return array; |
| | | } |
| | | |
| | | /** |