Skip to content
Advertisement

Checking connection to MySQL (Java)

I’m working on creating my little-utility for MySQL, and I need some help.
How I can check connection to MySQL (by login and password), like it was realised in phpMyAdmin, without pointing some database at first. Because most of solutions for work with databases need exactly that pointing.
Thanks in advance)

Advertisement

Answer

Yes. You can connect to the server without specifying the database in the connection 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);
    }
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement