温馨提示×

DriverManager的连接超时getConnection

小云
431
2023-09-27 10:17:17
栏目: 编程语言

在使用DriverManager.getConnection方法时,可以设置连接超时时间。连接超时是指在尝试建立数据库连接时等待的最大时间。如果超过了指定的连接超时时间仍然无法建立连接,将会抛出一个SQLException。

要设置连接超时时间,可以在获取连接之前调用DriverManager.setLoginTimeout方法,将超时时间以秒为单位作为参数传递。例如,以下代码将连接超时时间设置为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); // 设置连接超时时间为10秒

            String url = "jdbc:mysql://localhost:3306/mydatabase";

            String username = "myuser";

            String password = "mypassword";

            Connection connection = DriverManager.getConnection(url, username, password);

            // 使用connection对象执行数据库操作

            // 关闭连接

            connection.close();

        } catch (SQLException e) {

            e.printStackTrace();

        }

    }

}

在上述示例中,如果连接在10秒内无法建立,将会抛出一个SQLException。您可以根据需要进行适当的异常处理。

0