我在jdbc中使用localhost时发现了网络连接错误

时间:2014-08-01 07:34:04

标签: java mysql jdbc

我写了这个程序来连接我在同一台计算机上的数据库,但每次都发现了一个网络连接错误。 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)

2 个答案:

答案 0 :(得分:0)

此错误主要是由于Mysql服务器无法访问或未运行。请查看以下几点:

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.

答案 1 :(得分:0)

试试这个:

DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname","username","password");

如果未解决这个问题,请转到安装Mysql的地方并打开MySQL Notifier并检查服务器是否正在运行,如果没有启动它,然后尝试执行您的程序。