【问题标题】:Connecting to MySQL using jdbc driver [duplicate]使用 jdbc 驱动程序连接到 MySQL [重复]
【发布时间】:2016-09-07 17:22:39
【问题描述】:

我创建了一个名为 BD 的类,我在其中尝试与名为 bono 的数据库建立连接

public class BD {
String url,login,password,driver;
Connection conexion=null;

public BD(){
    driver = "com.mysql.jdbc.Driver";
    url = new String("jdbc:mysql://localhost:8000/bono");
    login = new String("root");
    password = new String("mypassword");
    try {
        Class.forName(driver);
        conexion = DriverManager.getConnection(url, login, password);
        System.out.println("Conexi�n con Base de datos Ok....");
    } catch (ClassNotFoundException e) { // 
        System.out.println("error 1");
    } catch (SQLException e) {
        System.out.println("error 2");
    }
}

但是当我执行它时,它只是停留在以下行中:

conexion = DriverManager.getConnection(url, login, password);

它不会发送任何错误,也不会建立连接。我该怎么办?

【问题讨论】:

  • 测试,添加异常捕获块
  • 或者干脆去掉端口部分,比如 jdbc:mysql://localhost/bono

标签: java mysql jdbc


【解决方案1】:

尝试将您的端口更改为 3306。

public class BD {
String url,login,password,driver;
Connection conexion=null;

public BD(){
    driver = "com.mysql.jdbc.Driver";
    url = new String("jdbc:mysql://localhost:3306/bono");
    login = new String("root");
    password = new String("mypassword");
    try {
        Class.forName(driver);
        conexion = DriverManager.getConnection(url, login, password);
        System.out.println("Conexi�n con Base de datos Ok....");
    } catch (ClassNotFoundException e) { // 
        System.out.println("error 1");
        e.printStackTrace();
    } catch (SQLException e) {
        System.out.println("error 2");
        e.printStackTrace();
    }
}

希望对你有帮助。

注意:确保 MySQL 正在运行。尝试类似: mysqladmin -u root -p status 来自您的控制台,不应该显示任何错误

【讨论】:

  • 尝试同时将异常消息添加到错误消息中
  • 当然,你是对的,现在已经添加了这些
【解决方案2】:

我认为您的端口可能不正确:请尝试此代码,至少您会看到一些异常

public class BD {
String url,login,password,driver;
Connection conexion=null;

public BD(){
    driver = "com.mysql.jdbc.Driver";
    url = new String("jdbc:mysql://127.0.0.1:3306/bono");
    login = new String("root");
    password = new String("mypassword");
    try {
        Class.forName(driver);
        conexion = DriverManager.getConnection(url, login, password);
        System.out.println("Ok....");
    } catch (ClassNotFoundException e) { // 
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

【讨论】:

    猜你喜欢
    • 2021-05-18
    • 1970-01-01
    • 2014-05-17
    • 1970-01-01
    • 2012-06-21
    • 1970-01-01
    • 1970-01-01
    • 2014-07-28
    相关资源
    最近更新 更多