0

我已经安装了MYSQLSERVER 5.1。然后我安装了 mysql-connector-java-3.0.8-stable-bin.jar 并将驱动器 c 放入文件夹 core 是 C:\core。然后在计算机的属性中我用变量创建用户变量命名 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:communication link failure:java.IO.Exception 根本原因:输入流意外结束

4

1 回答 1

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);
于 2013-06-07T15:29:34.087 回答