【问题标题】:Max value from auto commit false table自动提交假表的最大值
【发布时间】:2012-05-25 17:07:28
【问题描述】:

我的问题是我将表自动提交设置为 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();
}

【问题讨论】:

  • 这个站点应该叫做SQL Injection,而不是Stack Overflow。有没有人逃避过他们放在 SQL 语句中的东西?

标签: java mysql jsp commit rollback


【解决方案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 中查看更多信息

【讨论】:

  • 非常感谢您的回答,它对我有用。我会尝试使用准备好的语句
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-05
  • 1970-01-01
  • 2017-07-22
  • 2015-09-24
  • 1970-01-01
相关资源
最近更新 更多