我在答案通過擴大和CodeBolt anpadia做出如下完整的類。它只有一個靜態方法可以接受所有需要的連接參數,包括超時時間。另外,如果它們發生,該方法也會拋出SQLException和ClassNotFoundException。
用法:
String connectionUrl = "...";
String user = "...";
String password = "...";
String driver = "org.postgresql.Driver"; // for example
int timeoutInSeconds = 5;
Connection myConnection =
ConnectWithTimeout.getConnection(connectionUrl, user, password, driver, timeoutInSeconds);
下面是執行:
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class ConnectWithTimeout extends Thread {
private static String _url;
private static String _user;
private static String _password;
private static String _driver;
private static volatile Connection _connection = null;
private static volatile boolean _sleep = true;
private static volatile SQLException _sqlException = null;
private static volatile ClassNotFoundException _classNotFoundException = null;
@Override
public void run() {
try {
Class.forName(_driver);
_connection = DriverManager.getConnection(_url, _user, _password);
}
catch (SQLException ex) {
_sqlException = ex;
}
catch (ClassNotFoundException ex) {
_classNotFoundException = ex;
}
_sleep = false;
}
public static Connection getConnection(String url,
String user,
String password,
String driver,
int timeoutInSeconds)
throws SQLException, ClassNotFoundException {
checkStringOrThrow(url, "url");
checkStringOrThrow(user, "user");
checkStringOrThrow(password, "password");
checkStringOrThrow(driver, "driver");
if (timeoutInSeconds < 1) {
throw new IllegalArgumentException(
"timeoutInSeconds must be positive");
}
_url = url;
_user = user;
_password = password;
_driver = driver;
ConnectWithTimeout conn = new ConnectWithTimeout();
conn.start();
try {
for (int i = 0; i < timeoutInSeconds; i++) {
if (_sleep) {
Thread.sleep(1000);
}
}
}
catch (InterruptedException ex) {
}
if (_sqlException != null) {
throw _sqlException;
}
if (_classNotFoundException != null) {
throw _classNotFoundException;
}
return _connection;
}
private static void checkStringOrThrow(String variable, String variableName) {
if (variable == null || variable.length() == 0) {
throw new IllegalArgumentException(
"String is null or empty: " + variableName);
}
}
}
這是您使用和數據的基礎驅動程序? – 2011-01-31 12:51:49
我使用jdbc mysql驅動程序 – ihavprobs 2011-01-31 13:01:50