Advertisement
Guest User

Untitled

a guest
May 16th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1.  
  2. private static final int CONNECTION_TIMEOUT = 10000;
  3.  
  4. private Connection connection;
  5. private Properties connectionProps;
  6.  
  7. private DBSingleton() {}
  8.  
  9. public static DBSingleton get()
  10. {
  11. return DB;
  12. }
  13.  
  14. private boolean initialize()
  15. {
  16. connectionProps = new Properties();
  17. connectionProps.put("user", USERNAME);
  18. connectionProps.put("password", PASSWORD);
  19.  
  20. try
  21. {
  22. refreshConnection();
  23. return connection.isValid(CONNECTION_TIMEOUT);
  24. }
  25. catch(SQLException e)
  26. {
  27. e.printStackTrace();
  28. }
  29.  
  30. return false;
  31. }
  32.  
  33. private void refreshConnection()
  34. {
  35. try
  36. {
  37. Class.forName("com.mysql.jdbc.Driver");
  38. connection = DriverManager.getConnection("jdbc:mysql://"+IP+":"+PORT+"/"+DB_NAME,connectionProps);
  39. }
  40. catch(SQLException e)
  41. {
  42. e.printStackTrace();
  43. }
  44. catch(ClassNotFoundException e)
  45. {
  46. e.printStackTrace();
  47. }
  48. }
  49.  
  50. public Statement stmnt()
  51. {
  52. try
  53. {
  54. if(connection == null && !initialize()) //connection has not been established yet
  55. throw new RuntimeException();
  56.  
  57. if(!connection.isValid(CONNECTION_TIMEOUT))
  58. refreshConnection();
  59.  
  60. return connection.createStatement();
  61. }
  62. catch(SQLException e)
  63. {
  64. e.printStackTrace();
  65. }
  66.  
  67. return null;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement