如何修复列索引超出范围SQLException

Akk*_*kil 4 java mysql exception

当我通过查询时,我遇到了错误.

 Errorno is Nil
 Error String Is Query Problem.....
 java.sql.SQLException: Column Index out of range, 2 > 1.
Run Code Online (Sandbox Code Playgroud)

这是我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;
Run Code Online (Sandbox Code Playgroud)

cod*_*Man 10

错误在此声明中:

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

您必须在选择查询中选择所有12个字段.

例如:(我假设你的桌子上有12个字段stu_attendancemaster)这样做:

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

如果没有,你可以像这样修改你的查询语句

select `colName1`, `colName2`, `colName3`, `colName4`, `colName5`, `colName6`, `colName7`, `colName8`, `colName9`, `colName10`, `colName11`, `colName12`,  from stu_attendancemaster where classid=? and absentdt>=? and absentdt<=?
Run Code Online (Sandbox Code Playgroud)

注意:colName*应该是表中的实际列名.

编辑:如果您只需要来自查询的句点:只需拥有rs.getInt(1)并删除rs.getInt(2)rs.getInt(12)

经验法则是:select子句中的列数ResultSet.getXXX()应该相同.


Mat*_*ias 6

在语句中选择一列,然后在ResultSet中访问多个列.要解决您的问题,您必须从数据库中选择以后要从ResultSet中读取的内容.