java - How can I handle this exception within this method? -
i have jdbc connection code similiar following java jdbc tutorial:
public static void viewtable(connection con) throws sqlexception { statement stmt = null; string query = "select cof_name, sup_id, price, sales, total " + dbname + ".coffees"; try { stmt = con.createstatement(); resultset rs = stmt.executequery(query); while (rs.next()) { string coffeename = rs.getstring("cof_name"); int supplierid = rs.getint("sup_id"); float price = rs.getfloat("price"); int sales = rs.getint("sales"); int total = rs.getint("total"); system.out.println(coffeename + "\t" + supplierid + "\t" + price + "\t" + sales + "\t" + total); } } catch (sqlexception e ) { jdbctutorialutilities.printsqlexception(e); } { stmt.close(); } }
my problem way of handling connection closes statement in finally
block , method throws sqlexception may occur. don't want that, because want problems handled within class. however, do want statement#close()
call in block closed.
right i'm placing code in separate method returns hashmap
of fields returned exception handled in-class. there another, possibly better way handle this?
edit: close()
sqlexception 1 concerned with. if possible i'd handle within method. write try/catch in finally, seems awkward.
you have several problems:
you need close resultset explicitly. drivers less forgiving forgetting close resultset others, doesn't hurt sure close it.
you ought catch sqlexception thrown statement.close, because it's not interesting , serves mask interesting exception (if have in method throw exception, throws exception on way out, exception block , lose first exception). there isn't can if close method call throws exception, log , go on, not concerned about.
you should give on idea of handling sqlexceptions in method, sqlexception thrown statement.executequery 1 worthwhile , ought propagated if goes wrong. it's other code in application want know if sql here succeeded or not , that's throwing exceptions for.
personally i'd suggest using library ibatis or spring-jdbc this. jdbc error-prone , tedious , it's better take advantage of existing tools.
Comments
Post a Comment