Przeglądaj źródła

数据库查询

andy 1 rok temu
rodzic
commit
4882208e42
1 zmienionych plików z 20 dodań i 2 usunięć
  1. 20 2
      src/main/java/com/scbfkj/uni/process/DataBase.java

+ 20 - 2
src/main/java/com/scbfkj/uni/process/DataBase.java

@@ -37,8 +37,16 @@ public class DataBase {
 
         HikariPool dataSourcePool = getDataSourcePool(connectionStr);
         List<Map<String, Object>> result = argsList.parallelStream().flatMap(args -> {
-            try (Connection connection = dataSourcePool.getConnection();
-                 PreparedStatement preparedStatement = connection.prepareStatement(sql)
+            Connection connection = null;
+            try {
+                synchronized (dataSourcePool) {
+                    connection = dataSourcePool.getConnection();
+                }
+            } catch (SQLException e) {
+                throw new RuntimeException("数据库连接异常: %s\n sql: %s ;\n args: %s ".formatted(e.getMessage(), sql, DataFormatUtil.toString(args)));
+            }
+            try (
+                    PreparedStatement preparedStatement = connection.prepareStatement(sql)
             ) {
                 for (int i = 0; i < args.length; i++) {
                     preparedStatement.setObject(i + 1, args[i]);
@@ -47,6 +55,14 @@ public class DataBase {
                 return getResult(connectionStr, sql, resultSet).stream();
             } catch (Exception exception) {
                 throw new RuntimeException("数据异常: %s\n sql: %s ;\n args: %s ".formatted(exception.getMessage(), sql, DataFormatUtil.toString(args)));
+            } finally {
+                try {
+                    connection.close();
+                } catch (SQLException e) {
+                    if (Config.isDebug()) {
+                        e.printStackTrace();
+                    }
+                }
             }
         }).toList();
         String querySql = """
@@ -332,6 +348,8 @@ public class DataBase {
         }
         if (Objects.nonNull(driver)) {
             hikariConfig.setDriverClassName(driver);
+        } else {
+            hikariConfig.setDriverClassName("com.mysql.cj.jdbc.Driver");
         }
         if (Objects.nonNull(poolName)) {
             hikariConfig.setPoolName(poolName);