2013-06-20 30 views
4

當我傳遞一個查詢時,我得到低於錯誤。如何解決列索引超出範圍SQLException

Errorno is Nil 
Error String Is Query Problem..... 
java.sql.SQLException: Column Index out of range, 2 > 1. 

這是我的java方法中的代碼。

PreparedStatement pstm=con.prepareStatement("select period from stu_attendancemaster where classid=? and absentdt>=? and absentdt<=?"); 
pstm.setInt(1,classid); 
pstm.setDate(2,fromdt); 
pstm.setDate(3,todt); 
System.out.println("qry for prd "+pstm.toString()); 
rs=pstm.executeQuery(); 
System.out.println("after qry for prd "+pstm.toString()); 

if(rs.next()) { 
    stame = new Stu_AttendanceMasterEntity(rs.getInt(1), rs.getDate(2), rs.getInt(3), rs.getString(4), rs.getInt(5), rs.getString(6), rs.getTimestamp(7), rs.getString(8), rs.getTimestamp(9),rs.getString(10),rs.getInt(11),rs.getString(12)); 
} else { 
    flag=false; 
    errorstring=FN + P1 +" Class Name: " + Dep_ClassMasterDB.getClassname(classid) +" From Date: " +DateUtility.displayDate(fromdt,0) +" To Date: " +DateUtility.displayDate(todt,0) +N + V +DNE; 
} 
} catch(Exception e) { 
    flag=false; 
    errorstring="Query Problem..... "+e; 

回答

10

錯誤是在此聲明:

PreparedStatement pstm=con.prepareStatement("select period from stu_attendancemaster where classid=? and absentdt>=? and absentdt<=?"); 

您必須選擇都在你的選擇查詢的12場。

例如:(我假設你已經在你的表stu_attendancemaster 12場),這樣做:

PreparedStatement pstm=con.prepareStatement("select * from stu_attendancemaster where classid=? and absentdt>=? and absentdt<=?"); 

如果不是你可以修改您的查詢語句這樣

select `colName1`, `colName2`, `colName3`, `colName4`, `colName5`, `colName6`, `colName7`, `colName8`, `colName9`, `colName10`, `colName11`, `colName12`, from stu_attendancemaster where classid=? and absentdt>=? and absentdt<=? 

注意colName*應該是表中的實際列名稱。

編輯:在情況下,如果您需要查詢只期:只是有rs.getInt(1)和刪除rs.getInt(2)rs.getInt(12)

憑經驗是:列select子句中ResultSet.getXXX()數量和應相同。

+0

是的,但我想單獨使用這種方法的時期 – Akkil

+0

在這種情況下使用:rs.getInt(1)'。刪除'rs.getInt(2)'到'rs。 getInt(12)' – codeMan

+0

謝謝@codeman – Akkil

6

您在語句中選擇一列,然後訪問ResultSet中的多個列。 要解決您的問題,您必須從數據庫中選擇您以後想要從ResultSet中讀取的內容。

+0

你能多給點解釋嗎 – Akkil

+0

你的查詢「select from stu_attendancemaster where classid =?and absentdt> =?and absentdt <=?」只是從你的表中選擇列週期。 您正在評估的ResultSet訪問12個不同的列。 stame = new Stu_AttendanceMasterEntity(rs.getInt(1),rs.getDate(2),rs.getInt(3),... 但是隻有一個時間段可用 如果您訪問的列沒有選擇,你會收到你之前發佈的錯誤。 – Matthias

1

select語句是:

("select period from stu_attendancemaster where classid=? and absentdt>=? and absentdt<=?"); 

但是你在你的resultSet

rs.getInt(1), rs.getDate(2), rs.getInt(3), rs.getString(4), rs.getInt(5), rs.getString(6), rs.getTimestamp(7), rs.getString(8), rs.getTimestamp(9),rs.getString(10),rs.getInt(11),rs.getString(12)); 

當你只是選擇你不能從ResultSet這些數據變得比期間更多的領域。

+0

thanks @ melt321 – Akkil