我安装了 MYSQLSERVER 5.1 。然后我安装了mysql-connector-java-3.0.8-stable-bin.jar并将驱动器c放入文件夹核心C:\ core.Then在计算机属性中,我创建了变量名为CLASSPATH和变量值的用户变量:C:\ core \ mysql-connector-java-3.0.8-stable-bin.jar。
现在我已经创建了数据库EMPLOYEE4 我的java代码是:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
class MySQLTest{
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection dbcon = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/EMPLOYEE", "root", "root");
String query ="select count(*) from EMPLOYEE4 ";
Connection dbCon = null;
Statement stmt = null;
ResultSet rs = null;
//getting PreparedStatment to execute query
stmt = dbCon.prepareStatement(query);
//Resultset returned by query
rs = stmt.executeQuery(query);
while(rs.next()){
int count = rs.getInt(1);
System.out.println("count of stock : " + count);
}
} catch (Exception ex) {
ex.printStackTrace();
//Logger.getLogger(CollectionTest.class.getName()).log(Level.SEVERE, null, ex);
} finally{
//close connection ,stmt and resultset here
}
}
}
我得到的错误是java.sql.SQLEXCEPTION:通信链接失败:java.IO.Exception底层原因:意外的输入流结束
答案 0 :(得分:2)
你应该得到NPE。当您在dbCon
而非dbcon
// initialize here
Connection dbcon = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/EMPLOYEE", "root", "root");
String query ="select count(*) from EMPLOYEE4 ";
// Null here
Connection dbCon = null;
// on dbCon which is null
stmt = dbCon.prepareStatement(query);
修改强>
这是你的代码看起来的样子。
Connection dbcon = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/EMPLOYEE", "root", "root");
String query = "select count(*) from EMPLOYEE4 ";
Statement stmt = dbcon.createStatement();
ResultSet rs = stmt.executeQuery(query);