这个简单程序中的NullPointerException

时间:2013-04-29 05:08:35

标签: java sql jdbc nullpointerexception

任何人都可以帮助我吗?

package com.sample;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

public class DBClass {

    public static void main(String args[]) throws ClassNotFoundException,SQLException,Exception {

        Connection conn=null;

        PreparedStatement pstmt = null;

        ResultSet rs=null;


        try{
            Class.forName("oracle.jdbc.driver.OracleDriver");
            conn = DriverManager.getConnection("jdbc:oracle:thin:@172.24.137.30:1521:ORA10G","xxx","xxx");

            System.out.println("Before Query");
            pstmt=conn.prepareStatement("Select ROOM_NO from COHS_ROOM_ALLOTMENT where REQ_ID='RQ0011' and CUST_ID='CUS001'");
            System.out.println("Query is being executed");
            rs=pstmt.executeQuery(); 
            while (rs.next()) {
                System.out.println("Room No : "+rs.getInt(1));
            }
        }catch ( ClassNotFoundException claexp ){
            throw(claexp);
        }catch ( SQLException sqlexp ){
            throw(sqlexp);
        }catch ( Exception exp ){
            throw(exp);
        }finally{
            rs.close();
            pstmt.close();
            conn.close();
        }   
    }
}

4 个答案:

答案 0 :(得分:3)

finally{
    rs.close();
    pstmt.close();
    conn.close();
}  

应该是

 finally{
    if(rs!=null){try{rs.close();}catch(IOException e){}}
    //...
 }  

答案 1 :(得分:1)

如果使用java 7

Class.forName("oracle.jdbc.driver.OracleDriver");
try (Connection conn = DriverManager.getConnection(
        "jdbc:oracle:thin:@172.24.137.30:1521:ORA10G", "xxx", "xxx");) {
    System.out.println("Before Query");
    try (PreparedStatement pstmt = conn
            .prepareStatement("Select ROOM_NO from COHS_ROOM_ALLOTMENT where REQ_ID='RQ0011' and CUST_ID='CUS001'");) {
        System.out.println("Query is being executed");
        try (ResultSet rs = pstmt.executeQuery();) {
            while (rs.next()) {
                System.out.println("Room No : " + rs.getInt(1));
            }
        }
    }
}

答案 2 :(得分:0)

确保在classpath中有classes12.zip。

答案 3 :(得分:0)

如果您使用的是Java 7,则更喜欢使用Closable Connections和resultSets。像

try(Connection conn = DBManager.getConnection,Resultset ...

这样你就不必面对NullPointerExceptions