From 4fd3f760a30adf230f85b3e82d9a72af407266e7 Mon Sep 17 00:00:00 2001 From: 张洋洋 <10611411+yang-yang-z@user.noreply.gitee.com> Date: 星期四, 20 二月 2025 11:14:01 +0800 Subject: [PATCH] [add]服务发布 --- src/main/java/com/se/simu/utils/CsvToSQLiteUtils.java | 64 ++++++++++++++++++++++++++++++++ 1 files changed, 64 insertions(+), 0 deletions(-) diff --git a/src/main/java/com/se/simu/utils/CsvToSQLiteUtils.java b/src/main/java/com/se/simu/utils/CsvToSQLiteUtils.java index 46d9e63..85b398f 100644 --- a/src/main/java/com/se/simu/utils/CsvToSQLiteUtils.java +++ b/src/main/java/com/se/simu/utils/CsvToSQLiteUtils.java @@ -157,6 +157,35 @@ } } + /** + * 璇诲彇 CSV 淇濆瓨鏈湴 + * + * @param array 鏁版嵁 + * @param tableName 琛ㄥ悕绉� + */ + public static void readCsvSaveLocal(JSONArray array, String tableName) { + // 1. 鍒涘缓SQLite鏁版嵁搴撹繛鎺� + try (Connection conn = DriverManager.getConnection("jdbc:sqlite:rainfall.db")) { + if (conn != null) { + // 2. 鍒涘缓琛紙濡傛灉涓嶅瓨鍦級 + createTableIfNotExists(conn, tableName); + // 3. 璁剧疆SQLite杩炴帴鐨勫瓧绗︾紪鐮佷负UTF-8 + try (Statement stmt = conn.createStatement()) { + // 璁剧疆SQLite缂栫爜涓篣TF-8 + stmt.execute("PRAGMA encoding = 'UTF-8';"); + } + // 4. 寮�濮嬩簨鍔� + conn.setAutoCommit(false); + // 5. 璇诲彇CSV鏂囦欢骞舵彃鍏ユ暟鎹� + readCsvAndInsertDatas(array, conn, tableName); + // 6. 鎻愪氦浜嬪姟 + conn.commit(); + System.out.println("鏁版嵁鎴愬姛鎻掑叆鍒癝QLite鏁版嵁搴擄紒"); + } + } catch (SQLException e) { + System.err.println("SQLite杩炴帴澶辫触: " + e.getMessage()); + } + } /** * 璇诲彇 CSV 淇濆瓨鏈湴 @@ -190,6 +219,41 @@ return array; } + private static void readCsvAndInsertDatas(JSONArray array, Connection conn, String tableName) { + + String insertDataSql = "INSERT INTO " + tableName + " (station_name, rainfall, longitude, latitude, datetime) VALUES (?, ?, ?, ?, ?);"; + try (PreparedStatement pstmt = conn.prepareStatement(insertDataSql)) { + // 鎵归噺澶у皬 + int batchSize = 1000; + int count = 0; + for (int i = 0; i < array.size(); i++) { + JSONObject object = array.getJSONObject(i); + // 鑾峰彇姣忎竴鍒楃殑鏁版嵁 + String stationName = object.getString("stationName"); + double rainfall = object.getDouble("rainfall"); + double longitude = object.getDouble("longitude"); + double latitude = object.getDouble("latitude"); + String datetime = object.getString("datetime"); + // 璁剧疆鎻掑叆鏁版嵁鐨勫弬鏁� + pstmt.setString(1, stationName); + pstmt.setDouble(2, rainfall); + pstmt.setDouble(3, longitude); + pstmt.setDouble(4, latitude); + pstmt.setString(5, datetime); + // 娣诲姞鍒版壒澶勭悊 + pstmt.addBatch(); + count++; + // 姣廱atchSize鏉℃暟鎹墽琛屼竴娆℃壒閲忔彃鍏� + if (count % batchSize == 0) { + pstmt.executeBatch(); + } + } + // 鎵ц鍓╀綑鐨勬壒閲忔彃鍏� + pstmt.executeBatch(); + } catch (SQLException e) { + System.err.println("鎵归噺鎻掑叆鏁版嵁鏃跺嚭閿�: " + e.getMessage()); + } + } private static JSONArray readCsvAndInsertDatas(String csvFilePath, Connection conn, String tableName) { // 浣跨敤 Apache Commons CSV 璇诲彇CSV鏂囦欢 -- Gitblit v1.9.3