Advertisement
Guest User

Untitled

a guest
Sep 15th, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. package server;
  2.  
  3. import java.io.FileInputStream;
  4. import java.sql.Connection;
  5. import java.sql.DriverManager;
  6. import java.util.Properties;
  7. import java.util.logging.Level;
  8. import java.util.logging.Logger;
  9.  
  10.  
  11. public class Database {
  12.  
  13. private static final Logger LOG = Logger.getLogger(Database.class.getName());
  14. private static Properties props = new Properties();
  15. private static Connection conn = null;
  16. private static long lastUsed = System.currentTimeMillis();
  17.  
  18.  
  19. public static void init() throws Exception {
  20. LOG.log(Level.INFO, "initiating database connection...");
  21. try {
  22. FileInputStream fis = new FileInputStream("database.xml");
  23. props.loadFromXML(fis);
  24. } catch (Exception e) {
  25. LOG.log(Level.SEVERE, "error loading database properties", e);
  26. throw new Exception("error loading database properties");
  27. }
  28. connect();
  29. }
  30.  
  31. private static void connect() throws Exception {
  32. LOG.log(Level.INFO, "connecting to database...");
  33. try {
  34. Class.forName("com.mysql.jdbc.Driver").newInstance();
  35. } catch (Exception e) {
  36. LOG.log(Level.SEVERE, "error loading mysql driver", e);
  37. throw new Exception("error loading mysql driver");
  38. }
  39. try {
  40. conn = DriverManager.getConnection(
  41. "jdbc:mysql://" + props.getProperty("host") + ":"
  42. + props.getProperty("port") + "/"
  43. + props.getProperty("name"),
  44. props.getProperty("username"),
  45. props.getProperty("password"));
  46. } catch (Exception e) {
  47. LOG.log(Level.SEVERE, "error connecting to database", e);
  48. throw new Exception("error connecting to database "
  49. + e.getMessage());
  50. }
  51. }
  52.  
  53. public static Connection getConnection() throws Exception {
  54. if (conn == null) {
  55. throw new Exception("connection is null");
  56. }
  57. if (System.currentTimeMillis() - lastUsed > 300000) {
  58. try {
  59. lastUsed = System.currentTimeMillis();
  60. conn.close();
  61. connect();
  62. } catch (Exception e) {
  63. LOG.log(Level.SEVERE, "error refreshing database connection", e);
  64. throw new Exception("error refreshing database connection");
  65. }
  66. }
  67. return conn;
  68. }
  69.  
  70. public static void close() throws Exception {
  71. if (conn == null) {
  72. throw new Exception("connection is null");
  73. }
  74. conn.close();
  75. }
  76.  
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement