eclipse中用JDBC连Mysql出现错误Socket is not connected
eclipse中用JDBC连Mysql出现错误Socket is not connected
我在eclipse环境下建了一个Java Project,写了一个类JdbcTest.java
然后在这个项目下导入了mysql连接包mysql-connector-java-3.1.12-bin.jar
然后运行这个类,出现了如下错误:
com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.SocketException
MESSAGE: java.net.SocketException: Socket is not connected: connect
STACKTRACE:
java.net.SocketException: java.net.SocketException: Socket is not connected: connect
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:156)
at com.mysql.jdbc.MysqlIO. <init> (MysqlIO.java:284)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2555)
at com.mysql.jdbc.Connection. <init> (Connection.java:1485)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
at java.sql.DriverManager.getConnection(DriverManager.java:512)
at java.sql.DriverManager.getConnection(DriverManager.java:171)
at JdbcTest.go(JdbcTest.java:33)
at JdbcTest.main(JdbcTest.java:46)
** END NESTED EXCEPTION **
Last packet sent to the server was 32 ms ago.
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2621)
at com.mysql.jdbc.Connection. <init> (Connection.java:1485)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
at java.sql.DriverManager.getConnection(DriverManager.java:512)
at java.sql.DriverManager.getConnection(DriverManager.java:171)
at JdbcTest.go(JdbcTest.java:33)
at JdbcTest.main(JdbcTest.java:46)
我的类的源码如下:
import com.mysql.jdbc.Driver;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
/**
* @author tzq
*
*/
public class JdbcTest {
/**
* @param args
*/
String Driver = "com.mysql.jdbc.Driver ";
String URL = "jdbc:mysql://localhost:3306/ ";
String User = "root ";
String password = " ";
public void go(){
try {
Class.forName(Driver);
System.out.println( "Register Successful!!! ");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Connection con = DriverManager.getConnection(URL,User,password);
System.out.println( "Connection Successful!!! ");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
JdbcTest jdbctest = new JdbcTest();
jdbctest.go();
}
}
但是我在命令行模式下用javac,java,编译并运行没有错误,请问各位高手我的错误出在哪啊?
[解决办法]
String URL = "jdbc:mysql://localhost:3306/ ";
后面写上数据库的名字
String URL = "jdbc:mysql://localhost:3306/XXX ";