我的问题是我将表自动提交设置为 false。我需要从该表中获取最大 id(当前插入的自动增量 id 值)。但我得到了之前提交的进程的 ID。是否可以获取到值
我真正的问题是我需要向表中插入一些值,并且需要从第一个表中获取最后插入记录的 id 并将其插入到第二个表中。第二个插入还包括一些图像上传(作为代码的一部分)。所以需要一些延迟或者可能有异常(exception)。我需要通过发生任何异常来撤消所有插入(在第一个和第二个中)。我尝试为此使用提交-回滚方法。但正如我上面提到的,它不能正常工作。我的代码的主要部分写在下面
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();
}
最佳答案
自从
And need to take the id of the last inserted record from the first table and insert it to the second.
您可以使用新的 JDBC 3.0
方法 getGenerateKeys()
来获取生成的 ID。另一方面,您应该使用 PreparedStatement
来避免 SQL 注入(inject)。
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 中的更多信息
关于java - 自动提交错误表的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10647302/