Skip to content
Advertisement

java.sql.SQLException: Column Index out of range

i need a help when i execute the following MYSQL command in Navicat i get

mysql> SELECT Password FROM workers;

    +----------+
    | Password |
    +----------+
    | A        |
    | B        |
    | B        |
    | B        |
    | B        |

when i fire it in java i get

java.sql.SQLException: Column Index out of range, 3 > 2. 

Code :-

try {
       ArrayList<String> A = new ArrayList<String>();
       Class.forName("com.mysql.jdbc.Driver");
       Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employees", "root", "123456");
       Statement stmt = con.createStatement();
       ResultSet rs = stmt.executeQuery("SELECT Password FROM workers");
       int c =1;
       while(rs.next())  
       {
           A.add(rs.getString(c));
           c++;
       }
       con.close();
    } catch (Exception e) {
            System.out.println(e);
    }

Advertisement

Answer

Since you are only getting 1 column, you are out of range. You change your code as follows, and remove your counter.

try {
         ArrayList<String> A = new ArrayList<String>();
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employees", "root", "123456");
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT Password FROM workers");

        while(rs.next())  
        {
          A.add(rs.getString("Password"));

        }
        con.close();
    } catch (Exception e) {
        System.out.println(e);
    }
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement