Skip to content

Instantly share code, notes, and snippets.

@ghickman
Created Dec 16, 2010
Embed
What would you like to do?
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