What's wrong with my code about Mysql and JAVA -


private void jbutton1actionperformed(java.awt.event.actionevent evt) {         connectiondtb cdtb = new connectiondtb();  resultset rs = cdtb.retrievedata("select svcode listsv"); if(!rs.isbeforefirst()){         system.out.println("system null");         //add         cdtb.close();     } else{     while(rs.next()){         if(integer.parseint(jtextfield1.gettext()) == rs.getint("svcode")){                    system.out.println("error");             cdtb.close();             break;         }         else{             if(rs.islast()){                 //add                 cdtb.close();             }else{                 cdtb.close();         }  } 

my error is

apr 25, 2015 2:21:29 gui.them1 jbutton1actionperformed severe: null java.sql.sqlexception: operation not allowed after resultset closed

what did wrong?

it looks closing database connection inside loop, before done result set.

you can't close database connection if still using statements or resultsets associated database connection. (well, can it, closing connection close resultset, , kind of behavior observe.)

the normative pattern use try/catch/finally blocks, , close resultset(s), statements(s) , connection in block(s).

for example:

connectiondtb cdtb = null; resultset rs = null;  try {     cdtb = new connectiondtb();    rs = cdtb.retrievedata("select svcode listsv");     while(rs.next()){        // whatever processing need on each row,        // not close result set here        // not close database connection here!    }  } catch (sqlexception ex) {     // want if exception thrown } {     if (rs != null) {         try { rs.close(); } catch (sqlexception e) { /*ignore*/ }     }     if (cdtb != null) {         try { cdtb.close(); } catch (sqlexception e) { /*ignore*/ }     } } 

that finally block simplified, removing unnecessary try/catch. fine too:

} {     if (rs != null) {         rs.close();     }     if (cdtb != null) {         cdtb.close();     } } 

the important thing here closing in "finally" block, that's going run if exception occurs. , pattern, there 1 "close" of database connection, it's not multiple calls scattered through code.


some other notes:

it looks if code means "add" row if 1 doesn't exist. lot of overhead, pulling every value database , inspecting it.

it more efficient ask database if such row exists. ask database whether row exists, use statement this:

select svcode listsv svcode = ? 

prepare statement, bind value placeholder (the value looking for), , execute statement, , check if row returned or not.

if performing check see whether row needs added listsv table, use single insert ... select statement conditionally insert row.


Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -