自己投資の一つとしてチャレンジしている事を Blog で公開しています。今回は Microsoft JDBC Driver for SQL Server の接続文字列 (Connection String) について紹介します。(In English: Java – Connection String of Microsoft JDBC Driver for SQL Server)
———————————–
▼1. Microsoft JDBC Driver for SQL Server の接続文字列 (Connection String) について
———————————–
接続文字列には接続先の情報や認証情報に加え、login timeout、socket timeout、query timeout や application name なども指定できます (2020/05 の 最新の Microsoft JDBC Driver 8.2 for SQL Server)。
———————————–
▼2. Microsoft JDBC Driver for SQL Server の接続文字列 (Connection String) の指定例
———————————–
下記パラメータを接続文字列に追記しています。各種タイムアウト値を指定しリトライ処理を行うことで、ネットワークの一時的な問題や、クエリの実行が長時間終わらないなどの問題を回避します。
- loginTimeout (既定 15 秒) : 接続が失敗するまで Driver が待つ時間
- socketTimeout (既定 無限、単位 ミリ秒) : ソケットの read や accept に関するタイムアウトの時間
- queryTimeout (既定 無限、単位 秒) : クエリのタイムアウトの時間
- cancelQueryTimeout (既定 無限、単位 秒) : クエリがハングした場合や、SQL Server への TCP 接続が drop して例外処理が行われなかった場合にクエリがキャンセルされるまでの時間。queryTimeout の設定がある場合にのみ有効。
実際に接続パラメータを指定した例が以下です。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
public class ConnectionSQLSrvRetry2 {
private static final Logger log = LoggerFactory.getLogger(ConnectionSQLSrvRetry2.class);
public static void main(String[] args) throws InterruptedException {
Connection con = null;
boolean success = false;
int retryc = 0;
int max_retries = 3;
while (!success && retryc < max_retries) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://localhost:1433;" + "databaseName=TestDB;user=sa;password=password;loginTimeout=30;socketTimeout=60000;queryTimeout=60;cancelQueryTimeout=60;";
con = DriverManager.getConnection(connectionUrl);
System.out.println("Current Timestamps: " + new Timestamp(new Date().getTime()));
log.info("Connect to SQL Server successfully");
success = true;
} catch (ClassNotFoundException e) {
retryc++;
System.out.println("Current Timestamps: " + new Timestamp(new Date().getTime()));
log.error("Error Message: {}, retry count is {}", e, retryc);
// 30 seconds (30000 milliseconds) interval
Thread.sleep(30000);
} catch (SQLException se) {
retryc++;
System.out.println("Current Timestamps: " + new Timestamp(new Date().getTime()));
log.error("Error Messages: {}, retry count is {}", se, retryc);
// 30 seconds (30000 milliseconds) interval
Thread.sleep(30000);
}
}
try {
if (con != null) {
con.close();
System.out.println("Current Timestamps: " + new Timestamp(new Date().getTime()));
log.info("The connection is closed");
}else{
log.info("The connection was closed");
}
} catch (SQLException sec) {
System.out.println("Current Timestamps: " + new Timestamp(new Date().getTime()));
log.error("Error MEssages of fin ", sec);
}
}
}———————————–
▼3. 参考情報
———————————–
以上です。参考になりましたら幸いです。