使用JDBC调用sql server stored时获取java.lang.NullPointerException

时间:2016-01-11 06:38:47

标签: java sql-server stored-procedures jdbc

我试图通过JDBC调用数据库获取存储过程数据。当我执行下面的代码时,我得到resultset = null,我的代码中有什么错误?请指导我。

存储过程

CREATE PROCEDURE getEmpDetails
AS
BEGIN 
SELECT * FROM  Employees;
END

java文件

 // JDBC driver name and database URL
   static final String JDBC_DRIVER =   "com.microsoft.sqlserver.jdbc.SQLServerDriver";  
   static final String DB_URL =  "jdbc:sqlserver://localhost;database=JDBCDatabase";

   //  Database credentials
   static final String USER = "hj";
   static final String PASS = "kalpana";

   public static void main(String[] args) {
   Connection con = null;
   ResultSet rs = null;
   CallableStatement stmt = null;

   try{
          //STEP 2: Register JDBC driver
          Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

          //STEP 3: Open a connection
          System.out.println("Connecting to database...");
          con = DriverManager.getConnection(DB_URL,USER,PASS);

          //STEP 4: Execute a query
          System.out.println("Creating statement...");
         // stmt = conn.createStatement(); 

          stmt = con.prepareCall("{call getEmpDetails}");

          ResultSet resultSet  = stmt.getResultSet();

          System.out.println("resultset"+resultSet);

            if (resultSet.next()) {
                // Then we use a loop to retrieve rows and column data
                // and creates a html coded table output
                System.out.println("<table border='1' >");
                do {
                 System.out.println("<tr>");
                 System.out.print("<td>" + resultSet.getString("id") + "</td>");
                 System.out.print("<td>" + resultSet.getString("first") + "</td>");
                 System.out.println("<td>" + resultSet.getInt("last") + "</td>");
                 System.out.println("<td>" + resultSet.getDouble("age") + "</td>");
                 System.out.println("</tr>");
                } while (resultSet.next());
                System.out.println("</table>");
               }
   }catch(Exception e){
       e.printStackTrace();
   }finally{
       try {
           stmt.close();
           con.close();
          // input.close();
       } catch (SQLException e) {
           e.printStackTrace();
       }
   }

   }
}   

1 个答案:

答案 0 :(得分:1)

在您的代码中准备来电,然后您去期待结果 - 但不用执行查询。尝试将ResultSet上的访问者更改为查询的实际执行:

   stmt = con.prepareCall("{call getEmpDetails}"); 
   //Do it!
   ResultSet resultSet  = stmt.executeQuery();