Last active
March 31, 2016 15:47
-
-
Save saifazmi/ef64b0ca078930197b17 to your computer and use it in GitHub Desktop.
Java code to check if you have the PostgreSQL jdbc driver configured properly and if you can access your database. Replace the string values for the database property where necessary.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tests; | |
import database.properties.DBProperty; | |
import java.sql.Connection; | |
import java.sql.DriverManager; | |
import java.sql.SQLException; | |
import java.util.logging.Level; | |
import java.util.logging.Logger; | |
/** | |
* @author : saif | |
* @project : UniDB | |
* @date : 23/10/15 | |
*/ | |
public class TestDBConnection { | |
private static final Logger log = Logger.getLogger(DBProperty.class.getName()); | |
public static void main(String[] args) { | |
DBProperty dbProperty = new DBProperty(); | |
String serverURL = dbProperty.getServerURL(); | |
String dbName = dbProperty.getDbName(); | |
String url = serverURL+dbName; | |
String username = dbProperty.getUsername(); | |
String password = dbProperty.getPassword(); | |
try { | |
Class.forName("org.postgresql.Driver"); | |
} catch (ClassNotFoundException e) { | |
log.log(Level.SEVERE, e.toString(), e); | |
e.printStackTrace(); | |
} | |
log.log(Level.INFO, "PostgreSQL driver registered."); | |
Connection dbConn = null; | |
try { | |
dbConn = DriverManager.getConnection(url, username, password); | |
if (dbConn != null) { | |
log.log(Level.INFO, "Database accessed!"); | |
} else { | |
log.log(Level.SEVERE, "Failed to make dbConnection"); | |
} | |
} catch (SQLException e) { | |
log.log(Level.SEVERE, e.toString(), e); | |
e.printStackTrace(); | |
} finally { | |
try { | |
if (dbConn != null) | |
dbConn.close(); | |
} catch (SQLException e) { | |
log.log(Level.SEVERE, e.toString(), e); | |
e.printStackTrace(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment