我的测试程序是:
import java.io.*;
import java.sql.*;
public class DbUtil {
static String driverName="com.mysql.jdbc.Driver";
static String dbUrl="jdbc:mysql://";
static String user ="root";
static String password ="12345678";
public DbUtil() { }
public static java.sql.Connection connectToDb(String hostName, String databaseName)throws Exception
{
Connection connection=null;
String connName = dbUrl + hostName+":3306"+"/"+databaseName;
Class.forName(driverName).newInstance();
connection = DriverManager.getConnection(connName,user,password);
System.out.print("Connect to DB OK...");
return connection;
}
public static java.sql.Connection connectToDb(String databaseName)throws Exception{
return(connectToDb("localhost", databaseName));
}
public static java.sql.Connection connectToDb()throws Exception{
return(connectToDb("localhost", "addressbook"));
}
public static void main(String[] args)throws Exception{
try{
DbUtil db = new DbUtil();
db.connectToDb();
}catch(Exception e){
e.printStackTrace();
}
}
}
运行时出现如下错误:
java.sql.SQLException: Communication link failure: java.io.IOException, underlying cause: Unexpected end of input stream
** BEGIN NESTED EXCEPTION **
java.io.IOException
MESSAGE: Unexpected end of input stream
STACKTRACE:
java.io.IOException: Unexpected end of input stream
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:1096)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:626)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:1562)
at com.mysql.jdbc.Connection.<init>(Connection.java:491)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:346)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at addressbook.model.DbUtil.connectToDb(DbUtil.java:25)
at addressbook.model.DbUtil.connectToDb(DbUtil.java:36)
at addressbook.model.DbUtil.main(DbUtil.java:42)
** END NESTED EXCEPTION **
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:699)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:1562)
at com.mysql.jdbc.Connection.<init>(Connection.java:491)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:346)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at addressbook.model.DbUtil.connectToDb(DbUtil.java:25)
at addressbook.model.DbUtil.connectToDb(DbUtil.java:36)
at addressbook.model.DbUtil.main(DbUtil.java:42)
我在网上找了半天,试了N种方法,就是这句话一切都搞好了,希望碰到同样错误的人有所帮助"mysql>set password for user1@"localhost"=old_password('yourPassword');"
--转自