3

So I am trying to get the result as count from a sql query as follows

ResultSet rs = st.executeQuery("SELECT count(employeeID) FROM employee WHERE " +
                "employeeID='"+_empID+"' AND password = '"+_password + "'");

so i am also trying to convert that value to int and I tried the follwing

 for (; rs.next();) {
val =  (Integer) rs.getObject(1);
}

I have also try

val = Integer.parseInt(rs.getObject(1));

but nothing I get the following errors

java.lang.Long cannot be cast to java.lang.Integer

How can I do this.. so if that returns a 0,3 or 4 that it becomes an integer?

Thank you

EDITED TO: (STILL GETTING ERROR)

    long countLong = 0; 

        for (; rs.next();) {
           countLong = rs.getLong(1);
        }


       if(countLong < 1)
       {
         isAuthentic = false;
       }
       else
       {
         isAuthentic = true;
       }
user710502
  • 11,181
  • 29
  • 106
  • 161
  • This question was already asked, take a look. http://stackoverflow.com/questions/1590831/safely-casting-long-to-int-in-java – Jon Martin Jul 24 '11 at 23:14
  • Hello Jon, that did not help me.. I need to know how to get the value of the result set (database) and then make it something i can use to evaluate – user710502 Jul 24 '11 at 23:24

4 Answers4

10

A good trick to use when you are not sure about the exact number type is to cast it to the parent class of all numeric type, Number:

val =  ((Number) rs.getObject(1)).intValue();

This will work for all numeric types, eg float, long, int etc.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

Use ResultSet.getLong method:

long countLong = resultSet.getLong(1);
//if you really want and you are sure that it fits you can now cast
int count = (int)countLong; 
zacheusz
  • 8,750
  • 3
  • 36
  • 60
0

Cast it to a string and then to an int or long or whatever you want:

Integer.parseInt(rs.getObject(1).toString());
Scott123180
  • 91
  • 1
  • 11
0

Try a getString() and then Long.parseLong().

AHungerArtist
  • 9,332
  • 17
  • 73
  • 109