如何在java中将proj_id的值设置为max(proj_id)+ 1

时间:2011-04-20 09:14:29

标签: java jsp servlets

我正在尝试获取max(proj_id)+1的值并将值设置为vo然后我将数据插入db。我在下面的代码中尝试这个,但我得到空指针异常....

public final class CreateProjDAO 
{
private static InitialContext context;
String CLASS_NAME="DBConnectionFactory";
public void  submitProjectDetails(CreateProjVO createprojVO) 
{
    String methodname="createConnection";
    Connection conn  = null;
    PreparedStatement psmt;
    ResultSet rs=null;
    Statement st=null;
    int proj_id;
    try {
        conn = DBConnection.getJNDIConnection();

        rs=st.executeQuery("select MAX(PROJ_ID) from CR_PROJECT_DETAILS");

        if(!rs.next())
        {   
            proj_id=rs.getInt(1)+1;
            System.out.println("Max:"+proj_id);
        }
        else
        {
            proj_id=1;
             System.out.println("Max:"+proj_id);
        }

         createprojVO.setId(rs.getString(proj_id));

        System.out.println("in DAO");

       psmt= conn.prepareStatement("insert into CR_PROJECT_DETAILS(PROJ_ID,PROJ_NAME,PROJ_COST,PROJ_MANAGER) values(?,?,?,?)");
            psmt.setString(1, createprojVO.getId());
            psmt.setString(2,createprojVO.getName());
            psmt.setString(3,createprojVO.getCost());
            psmt.setString(4,createprojVO.getManager());
            psmt.executeQuery();


        System.out.println("conn==="+conn); 
        conn.close();
         System.out.println("Disconnected from database");

    } catch (Exception e) {
        e.printStackTrace(System.err);
        System.out.println("data already exist");
        System.out.println("error:"+e);

    } 

}
} 

1 个答案:

答案 0 :(得分:1)

rs=st.executeQuery("select MAX(PROJ_ID) from CR_PROJECT_DETAILS");
当语句被命中时,

st尚未被初始化,因此发生了NPE。