package test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLConnection {
public static Connection getConnection() throws InstantiationException,
IllegalAccessException, ClassNotFoundException, SQLException {
String driver = "com.mysql.jdbc.Driver";
String database = "MySQLDB";
String user = "root";
String password = "000000";
String url = "jdbc:mysql://127.0.0.1:3306/" +database+ "?user=" + user
+ "&password=" + password;
Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url);
return conn;
}
/**
*
*/
public MySQLConnection() {
super();
// TODO 自动生成构造函数存根
}
public static void main(String[] args) {
try {
getConnection();
System.out.println("success");
} catch (Exception e) {
System.out.println("failure!");
e.printStackTrace();
}
}
}
出现的异常:
failure!
com.mysql.jdbc.CommunicationsException: Communications link failure
Last packet sent to the server was 0 ms ago.
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1070)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2104)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:729)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:298)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:283)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at test.MySQLConnection.getConnection(MySQLConnection.java:20)
at test.MySQLConnection.main(MySQLConnection.java:35)
Caused by: 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:276)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2027)
... 7 more
解决的办法:
进入命令行模式查看端口:netstat -a
终于看到端口3306没有,原来是3307.