温馨提示×

Java DriverManager.getConnection()怎么连接数据库

小亿
93
2024-02-22 09:15:46
栏目: 编程语言

在Java中,可以使用DriverManager.getConnection()方法来连接数据库。首先,需要导入java.sql包,然后使用以下代码来连接数据库:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnection {
    public static void main(String[] args) {
        Connection connection = null;

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

        try {
            connection = DriverManager.getConnection(url, username, password);
            System.out.println("Database connected!");
        } catch (SQLException e) {
            System.out.println("Failed to connect to database!");
            e.printStackTrace();
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

在上面的代码中,需要替换url、username和password为实际的数据库连接信息。其中,url是数据库的连接地址,username和password分别是数据库的用户名和密码。在try-catch块中,调用DriverManager.getConnection()方法来连接数据库,如果连接成功则输出”Database connected!”,否则输出”Failed to connect to database!”。最后,在finally块中关闭数据库连接。

通过以上方式可以使用DriverManager.getConnection()方法来连接数据库。

0