检查与MySQL(Java)的连接

时间:2019-04-11 08:17:28

标签: java mysql jdbc database-connection

我正在为MySQL创建 little-utility ,我需要一些帮助。
我如何检查与MySQL 的连接(通过登录名和密码),就像在 phpMyAdmin 中实现的那样,而无需首先指向某些数据库。因为大多数用于数据库的解决方案都需要精确的指向。
先谢谢了

1 个答案:

答案 0 :(得分: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);
    }
}