0

我的问题是我将表自动提交设置为 false。我需要从该表中获取最大 ID(当前插入的自动增量 ID 值)。但我得到了前一个提交进程的 id。是否有可能获得价值

我真正的问题是我需要向表中插入一些值,并且需要从第一个表中获取最后插入记录的 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();
}
4

1 回答 1

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中的更多信息

于 2012-05-18T06:04:58.243 回答