java.sql.SQLException:列位置“1”超出范围

时间:2015-03-02 17:16:06

标签: java sqlexception

我有这个错误,我不明白,有人能告诉我我做错了吗?

java.sql.SQLException:列位置“1”超出范围。此ResultSet的列数为“0”。

public Object[][] searchFunction(String searchWord, String loginId) {
    Object[][] data = new Object[5][6];
    String[] tableName = {"subject", "sender", "recipient", "label", "message"};
    int nr = 0, i = 0, q = 1;
    boolean hasRows = false;
    for(int j = 0; j<5; j++) {
        try {    
            PreparedStatement prepareStatement = con.prepareStatement("SELECT * FROM messages WHERE sender = ? AND " + tableName[j] + " LIKE '%Done%' ORDER BY id ASC");    
            prepareStatement.setString(1, loginId);     
            rs = prepareStatement.executeQuery();
            while (rs.next()) {
                hasRows = true;
                boolean check = true;
                int id = rs.getInt("id");
                int priority = rs.getInt("priority");
                String recipient = rs.getString("recipient");
                String labelDb = rs.getString("label");
                String subject = rs.getString("subject");    
                String date = rs.getString("date");    
                String stars = setPriorityStars(priority);

                for(int k=0; k<i+1; k++) {
                    Object idObj = (Integer) id;
                    if(data[k][0] == idObj) check = false; 
                }

                if(check == true) {
                        data[i][0] = q;
                        data[i][1] = stars;
                        data[i][2] = recipient;
                        data[i][3] = labelDb;
                        data[i][4] = subject;
                        data[i][5] = date;
                        i++;
                        nr++;
                        q++;
                    }

            }
            if(hasRows == false) {
            data = getInbox(loginId);
            JOptionPane.showMessageDialog(null, "There is no fields that includes " + searchWord);
            break;
            }
        } catch(Exception ex) {
            System.out.println(ex);
        }
    }
    System.out.println("Found " + nr + " results");
    return data;
}

2 个答案:

答案 0 :(得分:0)

就在这里

 prepareStatement.setString(1, loginId); 

在您的查询中,您没有?来设置此值。如果登录ID不具有任何意义

,请将您的查询方面更改为loginid或删除此行

答案 1 :(得分:0)

它可能告诉您,loginId字符串中的值比名称为sender的数据库列长,并且您要将其与where子句进行比较。

此外,您编写的代码会泄漏大量内存,因为在循环的下一次迭代中创建新的代码之前,您没有关闭PreparedStatement。