Guest User

Untitled

a guest
Jan 31st, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. package dbUtils;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.SQLException;
  6. import java.util.logging.Level;
  7. import java.util.logging.Logger;
  8.  
  9. public class DBConnection {
  10.  
  11. private static final String user = "username";
  12. private static final String password = "password";
  13. private static final String url = "jdbc:mysql://www.host.com/databasename";
  14.  
  15. private static Connection globalConnection = getConnection();
  16.  
  17. //Auth connexion to the database
  18. public static Connection getConnection(){
  19. try {
  20. Connection connection = DriverManager.getConnection(url, user, password);
  21. System.out.println("Getting connected to mysql server...");
  22. System.out.println("Connection to remote database successfull");
  23.  
  24. return connection;
  25. } catch (SQLException ex) {
  26. Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
  27. return null;
  28. }
  29. }
  30.  
  31. //Portions of your program needing connection will use this getter, hence avoid auth reconnection all over again
  32. public static Connection getGlobalConnection() {
  33. return globalConnection;
  34. }
  35.  
  36. //Allows you to reconnect in case the global connection breaks for some reasons
  37. public static void setGlobalConnection(Connection globalConnection) {
  38. DBConnection.globalConnection = globalConnection;
  39. }
  40.  
  41. //Will close the connection to the database
  42. public static void closeGlobalConnection() {
  43. try {
  44. globalConnection.close();
  45. } catch (SQLException ex) {
  46. Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
  47. }
  48. }
  49. }
Add Comment
Please, Sign In to add comment