Search code examples
javamysqlcastingresultsetcomparable

How to cast A ResultSet object in to Comparable object


I am writing a generic Java code and i want to add integers to a min Heap which will be stored in a mysql database. For that i have written below code,

public void addElement(Comparable value) {

    sql = "INSERT INTO testHeap VALUES("+size+","+(int)value+ ") ";
    try {
        stmt.executeUpdate(sql);
        size++;
    } catch (SQLException ex) {
        Logger.getLogger(HeapMySql.class.getName()).log(Level.SEVERE, null, ex);
    }

    if(size == 0) throw new IllegalStateException("Shape error");
int index = size - 1;  
while(size != 0) {

        sql = "SELECT value FROM testHeap WHERE indexnum ="+index;
        T val;
        try {
            val = (T)stmt.executeQuery(sql);
                if(myParent(index).compareTo(val) <= 0) break; 

                    swap(parent(index), index); 
                    index = parent(index);
        } catch (SQLException ex) {
            Logger.getLogger(HeapMySql.class.getName()).log(Level.SEVERE, null, ex);
        }

}
}

This returns below exception in runtime

Exception in thread "main" java.lang.ClassCastException: com.mysql.jdbc.JDBC4ResultSet cannot be cast to java.lang.Comparable at Lab03.HeapMySql.addElement(HeapMySql.java:140)

I wan to know how to do this "val = (T)stmt.executeQuery(sql)" properly :)


Solution

  • You need to specify a column in the result set (even though there's only one)

    val = (T)new Integer(stmt.executeQuery(sql).getInt(1));
    

    As you commented below, you need an active row in your result set.

    You also need to close it after you're done or you'll run out of database cursors. Reading past the last row (using rs.next) will automatically close it, so I use a "while" instead of an "if".

    ResultSet rs = stmt.executeQuery(sql);
    while (rs.next()) {
        val = (T)new Integer(rs.getInt(1)))
    }