Home > Enterprise >  JDBC converting integer into a long from mysql database
JDBC converting integer into a long from mysql database

Time:12-24

I have a sql table that stores an object with a primary key that I called id. I have a method that collects the column values from the sql table and creates said object (each row in the DB corresponds to an object in java).

For example,

ArrayList<Object> objectList = new ArrayList<Object>();
Connection connection = createNewConnectionToDatabse();
PreparedStatement statement = connection.prepareStatement("SELECT * FROM objects;");
ResultSet rs = statement.executeQuery();
while(rs.next()){
     Object obj = new Obj(rs.getInt(1)); // rs.getInt(1) should return the integer id for the column...
     objectList.add(obj);
}

return objectList;

This was working fine a for the past few hours but for some reason a few moments ago, java started treating the result from the column id as a Long instead of an int. Now I keep getting an error that I cannot cast int onto a long but before it was returning the column id as an int. Why wont the JDBC return the int from the sql database as an int?

I also tried converting the long back into an int but 1) that still doens't explain why the code was working fine earlier and now it stopped working and 2) converting honestly doens't resolve the underlying issue here.

Any help will be greatly appreciated. Thank you.

CodePudding user response:

So I realized that the problem was in the fact that I was using the Integer class (I need access to null values) and as such rs.getInt() does not satisfy my problem because rs.getInt() will throw a null pointer exception if it detects a null (which my database will have). So I used (Integer) rs.getObject(1) to get the id's value in the table's first column. However, for some reason rs.getObject(1) returned a Long instead of an int when it detected a number value in the database. The solution happened to be to us rs.getObject(1, Integer.class) and that completely resolved the issue, and allowed me to continue my use of nulls and Integers.

CodePudding user response:

Can you try code below:

ArrayList<Object> objectList = new ArrayList<Object>();
Connection connection = createNewConnectionToDatabse();
PreparedStatement statement = connection.prepareStatement("SELECT * FROM objects;");
ResultSet rs = statement.executeQuery();
while(rs.next()){
     Object obj = new Obj(rs.getLong(1)); // rs.getLong(1) will return the long id for the column...
     objectList.add(obj);
}

return objectList;

We're changing the type of the id field in your Object class to long, by using the rs.getLong() method to retrieve the values from the id column instead of the rs.getInt() method.

Hopefully this will help!

  • Related