Created
December 16, 2010 17:04
-
-
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.
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 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