2012-05-18 44 views
0

我的問題是我設置了一個表自動提交false。我需要從該表中獲取最大ID(當前插入的自動遞增ID值)。但是我得到了以前承諾的流程的ID。是否有可能得到的價值自動提交最大值false表

我真正的問題是我需要插入表中的一些值,並需要從第一個表中插入最後插入的記錄的ID,並將其插入到第二個。第二次插入也包括一些圖片上傳(作爲代碼的一部分)。所以需要一些延遲或可以有例外。我需要通過發生任何異常來撤消所有的插入操作(包括第一個和第二個插入)。我試圖使用提交回滾方法。但它沒有正常工作,如上所述。我的代碼主要部分下面寫

try 
{ 

//getting connection and setting auto commit false 
dbHandler dbGetConnect=new dbHandler(); 
Connection conRegPlot=null; 
conRegPlot=dbGetConnect.getconn(); 
conRegPlot.setAutoCommit(false); 


String qryInsertPlot="INSERT INTO property_table(name,message,owner,locality,lattitude,longitude,country,state,city,type,catagory,created,modified,creted_date,zoompoint,mob_no,title,img_path,expire_date,lease_term) VALUES('none','"+description+"','"+sessionUserId+"','"+locality+"','"+lattitude+"','"+longitude+"','"+country+"','"+state+"','"+city+"','"+type+"','"+catagory+"',NOW(),NOW(),CURDATE(),'"+zoom+"','"+mob_no+"','"+title+"','NOT IN USE',"+expireDate+",'"+termsAndConditions+"')";//insertion into the first table 

Statement stCrs=conRegPlot.createStatement(); 
int resp=stCrs.executeUpdate(qryInsertPlot); 

String qryGetMaxProperty="SELECT MAX(l_id)"+ 
     " FROM property_table"+ 
      " WHERE stat='active'"+ 
      " AND CURDATE()<=expire_date"; 
propertyId1=dbInsertPropert.returnSingleValue(qryGetMaxProperty);// get the max id 


String qryInsertImage="INSERT INTO image_table(plot_id,ownr_id,created_date,created,modified,stat,img_path) VALUES('"+propertyId1+"','"+sessionUserId+"',CURDATE(),NOW(),NOW(),'active','"+img_pth+"')"; 

      Statement stImg=conRegPlot.createStatement(); 
      stImg.executeUpdate(qryInsertImage);// inserting the image 


conRegPlot.commit();  
} 
catch(Exception exc) 
{ 
    conRegPlot.rollback(); 

} 
finally{ 
    conRegPlot.close(); 
} 
+0

這個網站應該叫* SQL注入*,*不堆棧溢出*。有沒有人逃過他們在SQL語句中的東西? – tadman

回答

1

由於

,需要採取最後插入記錄的ID從第一 表,並將其插入到第二。

您可以使用新的JDBC 3.0方法getGeneratedKeys()獲取生成的ID。另一方面,您應該使用PreparedStatement來避免SQL注入。

PreparedStatement ps = null; 
try { 
    conn = getConnection(); 
    ps = conn.prepareStatement(myQuery, PreparedStatement.RETURN_GENERATED_KEYS); 
    ps.setInt(1, anInteger); 
    ... 
    int rows = ps.executeUpdate(); 
    if (rows == 1) { 
     ResultSet keysRS = ps.getGeneratedKeys(); 
     if (keysRS.next()) 
      int id = keysRS.getInt(1) // Get generated id 

對於MySQL,看多http://dev.mysql.com/doc/refman/5.1/en/connector-j-usagenotes-last-insert-id.html#connector-j-examples-autoincrement-getgeneratedkeys

+0

非常感謝您爲我解答的答案。我會盡量使用準備好的聲明 – arjuncc