Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package dbUtils;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- public class DBConnection {
- private static final String user = "username";
- private static final String password = "password";
- private static final String url = "jdbc:mysql://www.host.com/databasename";
- private static Connection globalConnection = getConnection();
- //Auth connexion to the database
- public static Connection getConnection(){
- try {
- Connection connection = DriverManager.getConnection(url, user, password);
- System.out.println("Getting connected to mysql server...");
- System.out.println("Connection to remote database successfull");
- return connection;
- } catch (SQLException ex) {
- Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
- return null;
- }
- }
- //Portions of your program needing connection will use this getter, hence avoid auth reconnection all over again
- public static Connection getGlobalConnection() {
- return globalConnection;
- }
- //Allows you to reconnect in case the global connection breaks for some reasons
- public static void setGlobalConnection(Connection globalConnection) {
- DBConnection.globalConnection = globalConnection;
- }
- //Will close the connection to the database
- public static void closeGlobalConnection() {
- try {
- globalConnection.close();
- } catch (SQLException ex) {
- Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- }
Add Comment
Please, Sign In to add comment