在 jdbc 中使用 localhost 时发现网络连接错误
Posted
技术标签:
【中文标题】在 jdbc 中使用 localhost 时发现网络连接错误【英文标题】:I found a net connection error while using localhost in jdbc 【发布时间】:2014-08-01 07:34:03 【问题描述】:我编写了这个程序来连接我在同一台计算机上的数据库,但我每次都发现网络连接错误。 com.mysql.jdbc.CommunicationsException:由于底层异常导致通信链接失败:
import java.sql.*;
public class Demo
public static void main(String[] args)
try
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/db","username","pwd");
Statement stmt = connection.createStatement();
String str="SHOW TABLES";
ResultSet resultSet=stmt.executeQuery(str);
while (resultSet.next())
System.out.println(resultSet.getString(1));
catch(Exception e)
e.printStackTrace();
我的 Stacktrace 是:-
com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.ConnectException
MESSAGE: Connection refused: connect
STACKTRACE:
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:271)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2771)
at com.mysql.jdbc.Connection.<init>(Connection.java:1555)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Demo.main(Demo.java:8)
** END NESTED EXCEPTION **
Last packet sent to the server was 0 ms ago.
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2847)
at com.mysql.jdbc.Connection.<init>(Connection.java:1555)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Demo.main(Demo.java:8)
【问题讨论】:
检查您的数据库配置。可能是防火墙问题或端口错误。 你的mysql服务运行了吗? 您的数据库服务器是否已启动并正在侦听端口3306
?
【参考方案1】:
试试这个:
DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname","username","password");
如果没有解决,请转到您安装 Mysql 的位置并打开 MySQL Notifier 并检查服务器是否正在运行,如果没有启动它,然后尝试执行您的程序。
【讨论】:
【参考方案2】:这个错误主要是因为Mysql server 无法访问或者没有运行。检查以下几点:
1. Check your DB Connection whether MYSQL is up and running.
2. Check if you are able to connect from command prompt
3. Restart the mysql server and try again.
【讨论】:
以上是关于在 jdbc 中使用 localhost 时发现网络连接错误的主要内容,如果未能解决你的问题,请参考以下文章
如何修复:“找不到适合 jdbc:mysql://localhost/dbname 的驱动程序”错误
运行时:java.lang.ClassNotFoundException:类 jdbc:db2:\/\/localhost:50000\/