Search code examples
javamysqldatabasejdbcresultset

JDBC Application - Column Index out of range, 0 < 1


I have this piece of code:

try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection con= DriverManager.getConnection(
                    "jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8","root","Icdjoil100"","root","Iconofcoil100");
            Statement stmt=con.createStatement();
            ResultSet rs=stmt.executeQuery("select user_id , user_name from t_user");
            while(rs.next()) {
                System.out.println(rs.getInt(0));
            }
            con.close();
        }catch(Exception e){
            e.printStackTrace();
        }

but I have this error when running the example:

java.sql.SQLException: Column Index out of range, 0 < 1.
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:910)
    at com.mysql.jdbc.ResultSet.checkColumnBounds(ResultSet.java:684)
    at com.mysql.jdbc.ResultSet.getInt(ResultSet.java:2621)
    at Test.main(Test.java:20)

Solution

  • JDBC (like SQL) is a 1-based API. I.e. column indexes start at 1. Write:

    rs.getInt(1);
    

    See ResultSet.getInt()

    columnIndex - the first column is 1, the second is 2, ...