826220679@qq.com
2025-08-07 4d6cd980c5c69e4d9d150669c89734642297e0cd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
package databases;
 
import java.io.*;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
 
import window.Windows;
 
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Collections;
import java.util.ArrayList;
import java.util.Arrays;
 
public class DBConnector {
    // ÅäÖòÎÊý
    private static String dbUser;
    private static String dbPass;
    private static String dbPort;
    private static String dbAddress;
    private static final String DB_NAME = "hxzk";
    static Connection conn;
    
    // ÓïÑÔÉèÖã¨Ä¬ÈÏÖÐÎÄ£©
    private static Locale currentLocale = Locale.SIMPLIFIED_CHINESE;
    private static ResourceBundle messages;
    
    // Îļþ·¾¶
    private static final String CONFIG_PATH = "systemfile/system.txt";
    private static final String LOG_DIR = "systemfile/";
    private static final String LANG_DIR = "systemfile/";
    
    static {
        // ¼ÓÔØÄ¬ÈÏÓïÑÔ
        setLanguage("zh");
        // ¼ÓÔØÅäÖÃÎļþ
        loadConfig();
    }
 
    // ÉèÖÃÓïÑÔ - ´Ó systemfile Îļþ¼Ð¼ÓÔØ
    public static void setLanguage(String langCode) {
        if ("en".equalsIgnoreCase(langCode)) {
            currentLocale = Locale.ENGLISH;
        } else {
            currentLocale = Locale.SIMPLIFIED_CHINESE;
        }
        
        // ³¢ÊÔ´Ó systemfile ¼ÓÔØÓïÑÔÎļþ
        messages = loadResourceBundle(currentLocale);
    }
 
    // ´ÓÎļþϵͳ¼ÓÔØ×ÊÔ´°ü
    private static ResourceBundle loadResourceBundle(Locale locale) {
        String langSuffix = locale.getLanguage();
        String fileName = "Messages_" + langSuffix + ".properties";
        File langFile = new File(LANG_DIR + fileName);
        
        // È·±£Ä¿Â¼´æÔÚ
        File langDir = new File(LANG_DIR);
        if (!langDir.exists()) {
            langDir.mkdirs();
        }
        
        // ³¢ÊÔ¼ÓÔØÎļþ
        if (langFile.exists()) {
            try (InputStream is = new FileInputStream(langFile)) {
                return new PropertyResourceBundle(is);
            } catch (IOException e) {
                System.err.println("ÓïÑÔÎļþ¼ÓÔØÊ§°Ü: " + e.getMessage());
            }
        }
        
        // Îļþ²»´æÔÚʱʹÓÃÄÚÖÃĬÈÏÖµ
        System.err.println("¾¯¸æ£ºÎ´ÕÒµ½ÓïÑÔÎļþ " + fileName + "£¬Ê¹ÓÃÄÚÖÃĬÈÏÏûÏ¢");
        return new ResourceBundle() {
            @Override
            protected Object handleGetObject(String key) {
                switch (key) {
                    case "CONFIG_READ_ERROR":return "ÅäÖÃÎļþ¶ÁÈ¡´íÎó";
                    case "INCOMPLETE_CONFIG":return "Êý¾Ý¿âÅäÖÃÐÅÏ¢²»ÍêÕû";
                    case "DB_CONNECTION_FAIL":return "Êý¾Ý¿âÁ¬½Óʧ°Ü";
                    case "LOG_WRITE_FAIL":return "ÈÕÖ¾ÎļþдÈëʧ°Ü";
                    case "DB_UPDATE_ERROR": return "Êý¾Ý¸üÐÂʧ°Ü";
                    case "DB_INSERT_ERROR": return "Êý¾Ý²åÈëʧ°Ü";
                    case "DB_DELETE_ERROR": return "Êý¾Ýɾ³ýʧ°Ü";
                    case "DB_TRUNCATE_ERROR": return "Çå¿Õ±íÊý¾Ýʧ°Ü";
                    case "FIELD_VALIDATION_FAIL": return "×Ö¶ÎÑé֤ʧ°Ü";
                    case "DEVICE_ID_EXISTS": return "É豸±àºÅÒÑ´æÔÚ";
                    case "INVALID_NUMBER_FORMAT": return "ÎÞЧµÄÊý×Ö¸ñʽ"; 
                    // Ìí¼ÓȱʧµÄ¼ü
                    case "DB_QUERY_ERROR": return "Êý¾Ý¿â²éѯʧ°Ü";
                    default: 
                        return key;
                }
            }
            
            @Override
            public Enumeration<String> getKeys() {
                return Collections.enumeration(
                    Arrays.asList(
                            "CONFIG_READ_ERROR", 
                            "INCOMPLETE_CONFIG", 
                            "DB_CONNECTION_FAIL", 
                            "LOG_WRITE_FAIL",
                            "DB_UPDATE_ERROR",
                            "DB_INSERT_ERROR",
                            "DB_DELETE_ERROR",
                            "DB_TRUNCATE_ERROR",
                            "FIELD_VALIDATION_FAIL",
                            "DEVICE_ID_EXISTS",
                            "INVALID_NUMBER_FORMAT",
                            "DB_QUERY_ERROR"  // Ìí¼ÓȱʧµÄ¼ü
                    )
                );
            }
        };
    }
 
    // ¼ÓÔØÅäÖÃÎļþ
    private static void loadConfig() {
        File configFile = new File(CONFIG_PATH);
        if (!configFile.exists()) {
            logError("CONFIG_READ_ERROR", "ÅäÖÃÎļþ²»´æÔÚ: " + CONFIG_PATH);
            return;
        }
        
        try (BufferedReader reader = new BufferedReader(new FileReader(configFile))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("dbName:")) {
                    dbUser = line.substring(7).trim();
                } else if (line.startsWith("dbPass:")) {
                    dbPass = line.substring(7).trim();
                } else if (line.startsWith("databaseport:")) {
                    dbPort = line.substring(13).trim();
                } else if (line.startsWith("databaseadress:")) {
                    dbAddress = line.substring(15).trim();
                }
            }
        } catch (IOException e) {
            logError("CONFIG_READ_ERROR", e.getMessage());
        }
    }
 
       
    private static void logError(String errorCode, String detail) {
        String logFileName = LOG_DIR + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "log.txt";
        
        // È·±£ÈÕ־Ŀ¼´æÔÚ
        File logDir = new File(LOG_DIR);
        if (!logDir.exists()) {
            logDir.mkdirs();
        }
        
        try (PrintWriter writer = new PrintWriter(new FileWriter(logFileName, true))) {
            String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            
            // °²È«»ñÈ¡×ÊÔ´×Ö·û´®£¬±ÜÃâMissingResourceException
            String message;
            try {
                message = messages.getString(errorCode);
            } catch (MissingResourceException e) {
                message = errorCode; // Ê¹ÓôíÎó´úÂë×÷Ϊ»ØÍËÏûÏ¢
            }
            
            if (detail != null) {
                message += ": " + detail;
            }
            
            writer.println("[" + timestamp + "] " + message);
        } catch (IOException e) {
            System.err.println("ÈÕ־дÈëʧ°Ü: " + e.getMessage());
        }
    }
 
    // Êý¾Ý¿âÁ¬½Ó·½·¨ - Ìí¼ÓUTF-8×Ö·û¼¯Ö§³Ö
    public static Connection connectToDatabase() {
        // ¼ì²éÅäÖÃÍêÕûÐÔ
        if (dbUser == null || dbPass == null || dbPort == null || dbAddress == null) {
            logError("INCOMPLETE_CONFIG", null);
            return null;
        }
 
        // Ìí¼Ó×Ö·û¼¯²ÎÊý£ºuseUnicode=true&characterEncoding=UTF-8
        String url = "jdbc:mysql://" + dbAddress + ":" + dbPort + "/" + DB_NAME + 
                     "?useUnicode=true&characterEncoding=UTF-8";
        
        Properties properties = new Properties();
        properties.setProperty("user", dbUser);
        properties.setProperty("password", dbPass);
        properties.setProperty("useSSL", "false");
        properties.setProperty("serverTimezone", "UTC");
 
        try {
           conn = DriverManager.getConnection(url, properties);
            return conn;
        } catch (SQLException e) {
            logError("DB_CONNECTION_FAIL", e.getMessage());
            return null;
        }
    }
    
    /**
     * ²éѯָ¶¨±íµÄËùÓÐÊý¾Ý
     * @param tableName Òª²éѯµÄ±íÃû
     * @return °üº¬±íÖÐËùÓÐÊý¾ÝµÄList£¬Ã¿¸öÔªËØÊÇÒ»¸öMap±íʾһÐÐÊý¾Ý
     */
    public static ResultSet queryTableData(String tableName) {            
        Statement stmt = null;
        ResultSet rs = null;
        
        // ÑéÖ¤±íÃûÓÐЧÐÔ
        if (tableName == null || tableName.trim().isEmpty()) {
            logError("DB_QUERY_ERROR", "ÎÞЧµÄ±íÃû: " + tableName);
            return rs;
        }
        
        try {
            conn = connectToDatabase();
            if (conn == null) {
                logError("DB_CONNECTION_FAIL", "ÎÞ·¨Á¬½Óµ½Êý¾Ý¿â");
                return rs;
            }
            
            stmt = conn.createStatement();
            String sql = "SELECT * FROM " + tableName;
            rs = stmt.executeQuery(sql);            
            
        } catch (SQLException e) {
            logError("DB_QUERY_ERROR", "²éѯ±í[" + tableName + "]ʧ°Ü: " + e.getMessage());
            e.printStackTrace();
        } 
        
        return rs;
    }
    
    public static void lianjieshujuku() {
         // ÉèÖÃÓïÑÔ£¨Ä¬ÈÏΪÖÐÎÄ£¬¿ÉÇл»ÎªÓ¢ÎÄ£©
        String language = "zh"; // Ä¬ÈÏÖÐÎÄ
        // String language = "en"; // Çл»ÎªÓ¢ÎÄ
        
        DBConnector.setLanguage(language);
        
        System.out.println("ÕýÔÚÁ¬½ÓÊý¾Ý¿â...");
        Connection conn = DBConnector.connectToDatabase();
        
        if (conn != null) {
            System.out.println("Êý¾Ý¿âÁ¬½Ó³É¹¦£¡");
            
            // ´´½¨²¢ÏÔʾ´°Ìå
            java.awt.EventQueue.invokeLater(() -> {
                Locale locale = "en".equals(language) ? Locale.ENGLISH : Locale.SIMPLIFIED_CHINESE;
                Windows window = new Windows("¶¨Î»¹ÜÀíϵͳ", conn, locale);
                window.setVisible(true);
            });
            
            // Ê¾Àý£ºÖ´Ðмòµ¥²éѯ
            try (java.sql.Statement stmt = conn.createStatement();
                 java.sql.ResultSet rs = stmt.executeQuery("SELECT VERSION()")) {
                
                if (rs.next()) {
                    System.out.println("MySQL°æ±¾: " + rs.getString(1));                   
                }
                
            } catch (Exception e) {
                System.err.println("²éѯʧ°Ü: " + e.getMessage());
            }
        } else {
            System.out.println("Êý¾Ý¿âÁ¬½Óʧ°Ü£¬Çë¼ì²éÈÕÖ¾Îļþ");
        }
    }
    
    // 1. ÐÞ¸ÄÊý¾Ý¿âÄÚÈÝ
    public static int updateData(String tableName, Map<String, String> fieldValues, int id) {
        if (fieldValues == null || fieldValues.isEmpty()) {
            return 0;
        }
        
        StringBuilder sql = new StringBuilder("UPDATE " + tableName + " SET ");
        List<String> values = new ArrayList<>();
        
        // ¹¹½¨SET×Ó¾ä
        for (Map.Entry<String, String> entry : fieldValues.entrySet()) {
            sql.append(entry.getKey()).append(" = ?, ");
            values.add(entry.getValue());
        }
        sql.delete(sql.length() - 2, sql.length()); // É¾³ý×îºóµÄ¶ººÅºÍ¿Õ¸ñ
        sql.append(" WHERE id = ?");
        
        try (Connection conn = connectToDatabase();
             PreparedStatement pstmt = conn.prepareStatement(sql.toString())) {
            
            // ÉèÖòÎÊý
            int index = 1;
            for (String value : values) {
                pstmt.setString(index++, value);
            }
            pstmt.setInt(index, id);
            
            return pstmt.executeUpdate();
        } catch (SQLException e) {
            logError("DB_UPDATE_ERROR", "±í: " + tableName + ", ID: " + id + ", ´íÎó: " + e.getMessage());
            return 0;
        }
    }
    
    // ÐÂÔö£º¸üÐÂϵͳÅäÖÃ×Ö¶Î
    // Ð޸ĸüз½·¨
    public static int updateSystemConfiguration(String field, String value) {
        String column = camelToUnderline(field); // ×ª»»×Ö¶ÎÃû
        Map<String, String> fieldValues = new HashMap<>();
        fieldValues.put(column, value);
        return updateData("system_configuration", fieldValues, 1);
    }
    // 2. ÐÂÔöÊý¾Ý¿âÄÚÈÝ
    public static int insertData(String tableName, Map<String, String> fieldValues) {
        if (fieldValues == null || fieldValues.isEmpty()) {
            return 0;
        }
        
        StringBuilder columns = new StringBuilder("(");
        StringBuilder placeholders = new StringBuilder("(");
        List<String> values = new ArrayList<>();
        
        // ¹¹½¨ÁÐÃûºÍռλ·û
        for (Map.Entry<String, String> entry : fieldValues.entrySet()) {
            columns.append(entry.getKey()).append(", ");
            placeholders.append("?, ");
            values.add(entry.getValue());
        }
        columns.delete(columns.length() - 2, columns.length()).append(")");
        placeholders.delete(placeholders.length() - 2, placeholders.length()).append(")");
        
        String sql = "INSERT INTO " + tableName + " " + columns + " VALUES " + placeholders;
        
        try (Connection conn = connectToDatabase();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            // ÉèÖòÎÊý
            for (int i = 0; i < values.size(); i++) {
                pstmt.setString(i + 1, values.get(i));
            }
            
            return pstmt.executeUpdate();
        } catch (SQLException e) {
            logError("DB_INSERT_ERROR", "±í: " + tableName + ", ´íÎó: " + e.getMessage());
            return 0;
        }
    }
 
    // 3. É¾³ýÖ¸¶¨Êý¾Ý
    public static int deleteDataById(String tableName, int id) {
        String sql = "DELETE FROM " + tableName + " WHERE id = ?";
        
        try (Connection conn = connectToDatabase();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setInt(1, id);
            return pstmt.executeUpdate();
        } catch (SQLException e) {
            logError("DB_DELETE_ERROR", "±í: " + tableName + ", ID: " + id + ", ´íÎó: " + e.getMessage());
            return 0;
        }
    }
 
    // 4. É¾³ýËùÓÐÊý¾Ý
    public static int truncateTable(String tableName) {
        String sql = "DELETE FROM " + tableName; // Ê¹ÓÃDELETE¶ø·ÇTRUNCATE
        
        try (Connection conn = connectToDatabase();
             Statement stmt = conn.createStatement()) {
            
            return stmt.executeUpdate(sql); // ·µ»ØÉ¾³ýµÄÐÐÊý
        } catch (SQLException e) {
            logError("DB_TRUNCATE_ERROR", "±í: " + tableName + ", ´íÎó: " + e.getMessage());
            return 0;
        }
    }
 
    /**
     * Ö´ÐÐSQL²éѯÓï¾ä
     * @param sql ÒªÖ´ÐеÄSQL²éѯÓï¾ä
     * @return ²éѯ½á¹û¼¯ResultSet
     */
    public static ResultSet executeQuery(String sql) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        
        try {
            conn = connectToDatabase();
            if (conn == null) {
                logError("DB_CONNECTION_FAIL", "ÎÞ·¨Á¬½Óµ½Êý¾Ý¿â");
                return null;
            }
            
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            return rs;
            
        } catch (SQLException e) {
            logError("DB_QUERY_ERROR", "Ö´ÐÐSQL²éѯʧ°Ü: " + e.getMessage() + "\nSQL: " + sql);
            e.printStackTrace();
            return null;
        }
        // ×¢Ò⣺µ÷ÓÃÕßÐèÒª×ÔÐйرÕResultSet¡¢StatementºÍConnection
    }
    
    /**
     * Ö´Ðж¯Ì¬¹¹½¨µÄSQL²éѯ
     * @param tableName ±íÃû
     * @param columns ²éѯµÄÁУ¨¶ººÅ·Ö¸ô£¬null±íʾËùÓÐÁУ©
     * @param whereClause WHEREÌõ¼þ£¨¿Énull£©
     * @param orderBy ORDER BY×Ӿ䣨¿Énull£©
     * @return ²éѯ½á¹û¼¯ResultSet
     */
    public static ResultSet executeQuery(String tableName, String columns, String whereClause, String orderBy) {
        // ÑéÖ¤±íÃûÓÐЧÐÔ
        if (tableName == null || tableName.trim().isEmpty()) {
            logError("DB_QUERY_ERROR", "ÎÞЧµÄ±íÃû: " + tableName);
            return null;
        }
        
        // ¹¹½¨SQLÓï¾ä
        StringBuilder sqlBuilder = new StringBuilder("SELECT ");
        sqlBuilder.append(columns != null ? columns : "*")
                  .append(" FROM ")
                  .append(tableName);
        
        if (whereClause != null && !whereClause.trim().isEmpty()) {
            sqlBuilder.append(" WHERE ").append(whereClause);
        }
        
        if (orderBy != null && !orderBy.trim().isEmpty()) {
            sqlBuilder.append(" ORDER BY ").append(orderBy);
        }
        
        // µ÷ÓÃͨÓòéѯ·½·¨
        return executeQuery(sqlBuilder.toString());
    }
    
    /**
     * Ö´Ðдø²ÎÊýµÄSQL¸üвÙ×÷£¨INSERT, UPDATE, DELETE£©
     * @param sql ´ø²ÎÊýµÄSQLÓï¾ä
     * @param params ²ÎÊýÁбí
     * @return ÊÜÓ°ÏìµÄÐÐÊý
     * @throws SQLException Èç¹ûÊý¾Ý¿â²Ù×÷ʧ°Ü
     */
    public static int executeUpdate(String sql, Object... params) throws SQLException {
        try (Connection conn = connectToDatabase();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            // ÉèÖòÎÊý
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i + 1, params[i]);
            }
            
            return pstmt.executeUpdate();
        } catch (SQLException e) {
            logError("DB_UPDATE_ERROR", "Ö´ÐÐSQL¸üÐÂʧ°Ü: " + e.getMessage() + "\nSQL: " + sql);
            throw e;
        }
    }
   
 // ÐÂÔö·½·¨£ºÍÕ·åתÏ»®Ïß
    public static String camelToUnderline(String camel) {
        if (camel == null || camel.isEmpty()) return camel;
        StringBuilder sb = new StringBuilder();
        for (char c : camel.toCharArray()) {
            if (Character.isUpperCase(c)) {
                sb.append('_').append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
 
 // Ìí¼Ó²ÎÊý»¯²éѯ·½·¨
    public static ResultSet executeQuery(String sql, Object... params) throws SQLException {
        Connection conn = connectToDatabase();
        if (conn == null) {
            throw new SQLException("ÎÞ·¨Á¬½Óµ½Êý¾Ý¿â");
        }
        PreparedStatement pstmt = conn.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            pstmt.setObject(i + 1, params[i]);
        }
        return pstmt.executeQuery();
    }
    
}