java - 连接到数据库 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;
}
}
解决方案
用户名和密码需要传递给 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 =("); } }
推荐阅读
- c# - 上传的文件附有 Guid Name ,而不仅仅是文件名
- javascript - 具有嵌套数据的材质 UI 数据网格
- networking - 为什么当oob连接到对等体时mpi等待很长时间?
- flutter - Flutter 是否为 Android/iOS 发布版本执行“Tree Shaking”/“Dart 死代码消除”?
- c++ - 在向量成员变量中存储线程触发断点
- javascript - 在添加新行时刷新 html 可编辑表 - Bootstable
- sql - 如何在 SUM() 的同一查询中使用 COUNT?
- django - 如何在 Django 中捕获对象的状态?
- svelte - 如何修复 sapper/svelte 中的 localStorage 错误
- python - 如何使用 python 中的 dict 配置(或其他方式)旋转 Gunicorn 访问和错误日志?