【问题标题】:Error occur while connecting to database mysql workbench:java.sql.SQLNonTransientConnectionException: Could not create connection to database server连接到数据库 mysql 工作台时发生错误:java.sql.SQLNonTransientConnectionException:无法创建与数据库服务器的连接
【发布时间】:2019-06-10 16:22:05
【问题描述】:

使用 MySQL-connector-java-5.1.44 和 mysql workbench 8 的 JDBC 连接错误

import java.sql.Connection;
import java.sql.DriverManager;

public class DB {
    public static Connection getConnection(){
        Connection con=null;
        try{
        Class.forName("com.mysql.jdbc.Driver");
            con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test?autoReconnect=true&useSSL=false");
        }catch(Exception e){System.out.println(e);}
        return con;
    }

}

【问题讨论】:

  • 您应该将用户名和密码传递给 getConnection
  • 你启动了数据库服务器了吗?您还需要提供UN和PW
  • 所以您可以从 MySQL Workbench 连接,但不能从您的 Java 应用程序连接?
  • 按照 Evgeni 的建议,您需要指定用户名和密码。如果这没有帮助,请将 System.out.println(e) 替换为 e.printStackTrace() 并在此处发布完整的堆栈跟踪。

标签: java eclipse macos jdbc mysql-workbench


【解决方案1】:

用户名和密码需要传递给 getConnection() 例如。

Connection conn = null; 
 String url = "jdbc:mysql://localhost/"; 
 String dbName = "someDb"; 
 String driver = "com.mysql.jdbc.Driver"; 
 String userName = "root"; String password = "password"; 
 try { Class.forName(driver).newInstance();
       conn = DriverManager.getConnection(url+dbName,userName,password);   System.out.println("Connected to the database"); conn.close(); System.out.println("Disconnected from database"); } catch (Exception e) { System.out.println("NO CONNECTION =("); } }

【讨论】:

    猜你喜欢
    • 2021-07-21
    • 2021-06-30
    • 1970-01-01
    • 2015-05-11
    • 2011-12-13
    • 2021-06-05
    • 1970-01-01
    • 2014-08-06
    • 2014-03-06
    相关资源
    最近更新 更多