-1

谁能帮我?

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

4 回答 4

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

应该

 finally{
    if(rs!=null){try{rs.close();}catch(IOException e){}}
    //...
 }  
于 2013-04-29T05:14:45.960 回答
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));
            }
        }
    }
}
于 2013-04-29T05:19:27.777 回答
0

如果您使用的是 java 7,那么更喜欢使用 Closable Connections 和 resultSets。喜欢

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

这样你就不必面对 NullPointerExceptions

于 2013-04-29T05:20:21.047 回答
0

确保类路径中有 classes12.zip。

于 2013-04-29T05:16:24.907 回答