]>
Commit | Line | Data |
---|---|---|
220bd904 L |
1 | package net.rizon;\r |
2 | \r | |
3 | import java.sql.Connection;\r | |
4 | import java.sql.DriverManager;\r | |
5 | import java.sql.SQLException;\r | |
6 | import java.util.Properties;\r | |
7 | \r | |
8 | public class DatabaseConnection {\r | |
9 | private static Connection con = null;\r | |
10 | private static Properties props = null;\r | |
11 | \r | |
12 | public static Connection getConnection() {\r | |
13 | if (props == null) throw new RuntimeException("DatabaseConnection not initialized");\r | |
14 | \r | |
15 | try {\r | |
16 | if((con != null) && con.isValid(2)) {\r | |
17 | return con;\r | |
18 | } else { // Attempt reconnect.\r | |
19 | if (con != null) con.close();\r | |
20 | \r | |
21 | DatabaseConnection.connect();\r | |
22 | \r | |
23 | if(con == null) {\r | |
24 | throw new RuntimeException("MySQL server has gone away. Attempted reconnection failed.");\r | |
25 | }\r | |
26 | \r | |
27 | return con;\r | |
28 | }\r | |
29 | }\r | |
30 | catch (SQLException e) {\r | |
31 | e.printStackTrace();\r | |
32 | }\r | |
d9645dc7 L |
33 | catch (AbstractMethodError e) {\r |
34 | DatabaseConnection.connect();\r | |
35 | \r | |
36 | if(con == null) {\r | |
37 | throw new RuntimeException("MySQL server has gone away. Attempted reconnection failed.");\r | |
38 | }\r | |
39 | \r | |
40 | return con;\r | |
41 | }\r | |
220bd904 L |
42 | return con;\r |
43 | }\r | |
44 | \r | |
45 | public static boolean isInitialized() {\r | |
46 | return props != null;\r | |
47 | }\r | |
48 | \r | |
49 | public static void setProps(Properties aProps) {\r | |
50 | props = aProps;\r | |
51 | }\r | |
52 | \r | |
53 | private static void connect() {\r | |
54 | String driver = props.getProperty("sqlDriver");\r | |
55 | String url = props.getProperty("sqlUrl");\r | |
56 | String user = props.getProperty("sqlUser");\r | |
57 | String password = props.getProperty("sqlPass");\r | |
58 | \r | |
59 | try {\r | |
60 | Class.forName(driver);\r | |
61 | } catch (ClassNotFoundException e) {\r | |
62 | e.printStackTrace();\r | |
63 | }\r | |
64 | try {\r | |
65 | con = DriverManager.getConnection(url, user, password);\r | |
66 | } catch (SQLException e) {\r | |
67 | e.printStackTrace();\r | |
68 | throw new RuntimeException("Error connecting to MySQL: " + e.getMessage());\r | |
69 | }\r | |
70 | }\r | |
71 | }\r |