Skip to content

Instantly share code, notes, and snippets.

@scan
Created January 29, 2015 12:40
Show Gist options
  • Save scan/05ab156afb074d2058b0 to your computer and use it in GitHub Desktop.
Save scan/05ab156afb074d2058b0 to your computer and use it in GitHub Desktop.
A simple class to check connections with JDBC
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class Connector {
private static final String USERNAME = "username";
private static final String PASSWORD = "password";
private static final String HOST = "localhost";
private static final short PORT = 3306;
private static final String DBNAME = "mysql";
private static final String CONNECTION_STRING = "jdbc:mysql://" + HOST + ':' + PORT + '/' + DBNAME;
public static void main(String[] args) {
(new Connector()).run();
}
public void run() {
Connection conn = null;
try {
// Try to find driver class
Class.forName("com.mysql.jdbc.Driver");
conn = getConnection();
System.out.println(conn.toString());
} catch (SQLException e) {
System.err.println("Error with connection");
e.printStackTrace(System.err);
} catch (ClassNotFoundException e) {
System.err.println("Driver class not found");
e.printStackTrace(System.err);
} finally {
if (conn != null) {
try {
conn.close();
System.out.println("Connection closed");
} catch (SQLException e) {
e.printStackTrace(System.err);
}
}
}
}
public Connection getConnection() throws SQLException {
Connection conn = null;
final Properties connectionProps = new Properties();
connectionProps.put("user", USERNAME);
connectionProps.put("password", PASSWORD);
conn = DriverManager.getConnection(CONNECTION_STRING, connectionProps);
System.out.println("Connected to database");
return conn;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment