Skip to content

Instantly share code, notes, and snippets.

@ghickman
Created December 16, 2010 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghickman/743656 to your computer and use it in GitHub Desktop.
Save ghickman/743656 to your computer and use it in GitHub Desktop.
Check the validity of a MySQL connection profile in a Java app. Requires the mysql jdbc connector.
package dbtest;
import java.sql.*;
/**
*
* @author George Hickman <george@ghickman.co.uk>
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://192.168.1.10/eaton";
String user = "george";
String pwd = "madnashua";
boolean bConnected = checkConnection(driver, url, user, pwd);
if (bConnected) {
printLine("Connection successful.");
} else {
printLine("Connection failed.");
}
}
public static boolean checkConnection(String driver, String url, String user, String pwd) {
// attempt to get a connection to the data source using the given
// driver, url, user, and password
Connection connection = null;
boolean bConnected = false;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, user, pwd);
bConnected = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException se) {
}
connection = null;
}
return bConnected;
}
}
public static void printLine(String msg) {
System.out.println(msg);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment