首页 > 解决方案 > 连接到数据库 mysql 工作台时发生错误:java.sql.SQLNonTransientConnectionException:无法创建与数据库服务器的连接

问题描述

使用 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;
    }

}

标签: javaeclipsemacosjdbcmysql-workbench

解决方案


用户名和密码需要传递给 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 =("); } }

推荐阅读