在使用DriverManager.getConnection方法時(shí),可以設(shè)置連接超時(shí)時(shí)間。連接超時(shí)是指在嘗試建立數(shù)據(jù)庫(kù)連接時(shí)等待的最大時(shí)間。如果超過(guò)了指定的連接超時(shí)時(shí)間仍然無(wú)法建立連接,將會(huì)拋出一個(gè)SQLException。
要設(shè)置連接超時(shí)時(shí)間,可以在獲取連接之前調(diào)用DriverManager.setLoginTimeout方法,將超時(shí)時(shí)間以秒為單位作為參數(shù)傳遞。例如,以下代碼將連接超時(shí)時(shí)間設(shè)置為10秒:
import java.sql.Connection;import java.sql.DriverManager;
import java.sql.SQLException;
public class Example {
public static void main(String[] args) {
try {
DriverManager.setLoginTimeout(10); // 設(shè)置連接超時(shí)時(shí)間為10秒
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "myuser";
String password = "mypassword";
Connection connection = DriverManager.getConnection(url, username, password);
// 使用connection對(duì)象執(zhí)行數(shù)據(jù)庫(kù)操作
// 關(guān)閉連接
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
在上述示例中,如果連接在10秒內(nèi)無(wú)法建立,將會(huì)拋出一個(gè)SQLException。您可以根據(jù)需要進(jìn)行適當(dāng)?shù)漠惓L幚怼?/span>