帮我写一段关于DriverManager.getConnection如果连接失败的try catch代码段
时间: 2023-07-01 21:28:22 浏览: 62
当使用`DriverManager.getConnection`连接数据库时,我们可以使用try-catch块来捕获连接过程中可能会出现的异常,例如:
```java
import java.sql.*;
public class ConnectionExample {
public static void main(String[] args) {
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
} catch (SQLException e) {
System.out.println("Connection failed: " + e.getMessage());
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
}
```
在上面的示例中,我们尝试连接到名为`mydatabase`的MySQL数据库。如果连接失败,我们将在控制台上打印出失败的消息。无论连接成功或失败,我们都将在finally块中关闭连接以避免资源泄漏。