检查与MySQL的连接(Java)

问题描述 投票:1回答:1

我正在为MySQL创建我的小实用程序,我需要一些帮助。 我如何检查与MySQL的连接(通过登录和密码),就像在phpMyAdmin中实现的那样,而不是首先指向一些数据库。因为大多数使用数据库的解决方案都需要完全指向。 提前致谢)

java mysql jdbc database-connection
1个回答
0
投票

是。您可以连接到服务器,而无需在连接URL中指定数据库。

public static void main(String[] args) {
    String url = "jdbc:mysql://localhost:3306"; //pointing to no database.
    String username = "myusername";
    String password = "mypassword";

    System.out.println("Connecting to server...");

    try (Connection connection = DriverManager.getConnection(url, username, password)) {
        System.out.println("Server connected!");
        Statement stmt = null;
        ResultSet resultset = null;

        try {
            stmt = connection.createStatement();
            resultset = stmt.executeQuery("SHOW DATABASES;");

            if (stmt.execute("SHOW DATABASES;")) {
                resultset = stmt.getResultSet();
            }

            while (resultset.next()) {
                System.out.println(resultset.getString("Database"));
            }
        }
        catch (SQLException ex){
            // handle any errors
            ex.printStackTrace();
        }
        finally {
            // release resources
            if (resultset != null) {
                try {
                    resultset.close();
                } catch (SQLException sqlEx) { }
                resultset = null;
            }

            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException sqlEx) { }
                stmt = null;
            }

            if (connection != null) {
                connection.close();
            }
        }
    } catch (SQLException e) {
        throw new IllegalStateException("Cannot connect the server!", e);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.