Search code examples
javasqlhsqldb

Statement return wrong values


I have a JAVA Application which uses HSQLDB. There is a table called 'tblUser' containing a column bigint type called 'tongHH'. If I use the HSQLDB DatabaseManager to run the following query:

select sum(tongHH) from tblUser. 

The DBM returns the right values If I use the following JAVA Code to read out this data with the same query, java always prints wrong value. i getting 65 and i expected 3905

public int getParentID(String query) {
    int a = 0;
    Connection conn = null;
    ResultSet rs = null;
    try {
       conn = MyConection.getConnection();
       Statement st = conn.createStatement();
       rs = st.executeQuery(query);
while(rs.next()){
    a=rs.getByte(1);
}
} catch (Exception e) {
    e.printStackTrace();
    }finally{
        try {         
            MyConection.closeConnection(conn, null, rs);
        } catch (Exception e) {
        }
    }
return a;
}

Solution

  • You are overflowing the byte you are attempting to retrieve from the ResultSet.

    The value 3905 as an int is:

    00000000 00000000 00001111 01000001
    

    Getting the value as a byte only keeps the last 8 bits, or

    01000001
    

    which is 65.

    Call the getInt method instead.