skip to Main Content

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)

2

Answers


  1. 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);
        }
    }
    
    Login or Signup to reply.
  2. The only comment is that if you know the username and password, I’d edit to those details.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search