Guest User

Untitled

a guest
Aug 23rd, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 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. public static void init() throws Exception {
  19. //LOG.log(Level.INFO, "initiating database connection...");
  20. try {
  21. FileInputStream fis = new FileInputStream("database.xml");
  22. props.loadFromXML(fis);
  23. } catch (Exception e) {
  24. //LOG.log(Level.SEVERE, "error loading database properties", e);
  25. throw new Exception("error loading database properties");
  26. }
  27. connect();
  28. }
  29.  
  30. private static void connect() throws Exception {
  31. //LOG.log(Level.INFO, "connecting to database...");
  32. try {
  33. Class.forName("com.mysql.jdbc.Driver").newInstance();
  34. } catch (Exception e) {
  35. //LOG.log(Level.SEVERE, "error loading mysql driver", e);
  36. throw new Exception("error loading mysql driver");
  37. }
  38. try {
  39. conn = DriverManager.getConnection(
  40. "jdbc:mysql://" + props.getProperty("host") + ":"
  41. + props.getProperty("port") + "/"
  42. + props.getProperty("name"),
  43. props.getProperty("username"),
  44. props.getProperty("password"));
  45. } catch (Exception e) {
  46. //LOG.log(Level.SEVERE, "error connecting to database", e);
  47. throw new Exception("error connecting to database "
  48. + e.getMessage());
  49. }
  50. }
  51.  
  52. public static Connection getConnection() throws Exception {
  53. if (conn == null) {
  54. throw new Exception("connection is null");
  55. }
  56. if (System.currentTimeMillis() - lastUsed > 300) {
  57. try {
  58. lastUsed = System.currentTimeMillis();
  59. conn.close();
  60. connect();
  61. } catch (Exception e) {
  62. //LOG.log(Level.SEVERE, "error refreshing database connection", e);
  63. throw new Exception("error refreshing database connection");
  64. }
  65. }
  66. return conn;
  67. }
  68.  
  69. public static void close() throws Exception {
  70. if (conn == null) {
  71. throw new Exception("connection is null");
  72. }
  73. conn.close();
  74. }
  75.  
  76. }
Add Comment
Please, Sign In to add comment