是想要針對查詢到的資料進行一些簡單的新增、更新或刪除資料,您可以藉由ResultSet的一些方法來執行

如果您只是想要針對查詢到的資料進行一些簡單的新增、更新或刪除資料,您可以藉由ResultSet的一些方法來執行,而不一定要撰寫SQL並執行。  
 
想要使用ResultSet直接進行新增、更新或刪除資料,在建立Statement時必須在createStatement()上指定  ResultSet.TYPE_SCROLL_SENSITIVE(或ResultSet.TYPE_SCROLL_INSENSITIVE,如果不想取得更新後的資料的話)與ResultSet.CONCUR_UPDATABLE,例如:  
 
Statement  stmt  =    conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,      
                                                       ResultSet.CONCUR_UPDATABLE);    
   
 
 
假如我們想要針對查詢到的資料進行更新的動作,我們先移動游標至想要更新的資料位置,然後使用updateXXX()等對應的方法即可,最後記得使用  updateRow()讓更新生效,例如:  
 
ResultSet  result  =  stmt.executeQuery(  
                       "SELECT  *  FROM  message  WHERE  name='caterpillar'");    
   
result.last();    
result.updateString("name",  "justin");    
result.updateString("email",  "justin@mail.com");    
   
result.updateRow();    
 
   
 
使用updateXXX()等方法之後,並不會馬上對資料庫生效,而必須執行完updateRow()方法才會對資料庫進行操作,如果在  updateRow()前想要取消之前的updateXXX()方法,則可以使用cancelRowUpdates()方法取消。  
 
如果想要新增資料,則先使用moveToInsertRow()移至新增資料處,執行相對的updateXXX()方法,然後再執行insertRow  ()即可新增資料,例如:  
 
ResultSet  result  =  stmt.executeQuery(  
                       "SELECT  *  FROM  message  WHERE  name='caterpillar'");    
   
result.moveInsertRow();    
result.updateString("name",  "caterpillar");    
result.updateString("email",  "caterpillar@mail.com");    
result.updateString("subject",  "test");    
result.updateString("memo",  "This  is  a  test!");    
   
result.insertRow();    
 
   
如果想要刪除查詢到的某筆資料,則可以將游標移至該筆資料,然後執行deleteRow()方法即可:  
 
ResultSet  result  =  stmt.executeQuery(  
                       "SELECT  *  FROM  message  WHERE  name='caterpillar'");    
   
result.last();    
result.deleteRow();    
 
 
 
---------------------------------------------------------------  
 
Statement  stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATBALE);  
ResultSet  uprs=stmt.executeQuery("select  username,sex  from  talbe_name");  
uprs.last();  
uprs.updateString(1,"aaa");  
uprs.updateString(2,"男");  
uprs.updateRow();  
原文地址:https://www.cnblogs.com/chinatefl/p/1214776.html