【问题标题】:Checking connection to MySQL (Java)检查与 MySQL (Java) 的连接
【发布时间】:2019-09-01 19:28:42
【问题描述】:

我正在为 MySQL 创建我的 little-utility,我需要一些帮助。
我如何检查与 MySQL 的连接(通过登录名和密码),就像在 phpMyAdmin 中实现的那样,一开始不指向某个数据库。因为大多数使用数据库的解决方案都需要准确地指出这一点。
提前致谢)

【问题讨论】:

  • 也许我读错了,但听起来您想检查是否可以连接到数据库而不连接到该数据库?
  • 其实没有)我想检查与主机的连接,数据库所在的位置...

标签: java mysql jdbc database-connection


【解决方案1】:

唯一的评论是,如果您知道用户名和密码,我会编辑这些详细信息。

【讨论】:

    【解决方案2】:

    是的。您可以连接到服务器,而无需在连接 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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-27
      • 2017-11-11
      • 1970-01-01
      • 1970-01-01
      • 2016-02-12
      相关资源
      最近更新 更多