0

私の問題は、テーブルの自動コミットを false に設定したことです。そのテーブルから最大IDを取得する必要があります(現在挿入されている自動インクリメントIDの値)。しかし、以前にコミットされたプロセスのIDを取得しています。値を取得することは可能ですか

私の本当の問題は、いくつかの値をテーブルに挿入する必要があり、最初のテーブルから最後に挿入されたレコードの ID を取得し、それを 2 番目のテーブルに挿入する必要があることです。2 番目の挿入には、(コードの一部として) 画像のアップロードも含まれます。そのため、多少の遅延が発生するか、例外が発生する可能性があります。例外を発生させて、すべての挿入 (最初と 2 番目の両方) を元に戻す必要があります。これには commit-roll back メソッドを使用しようとしました。しかし、上記のように適切に機能していません。私のコードの主要部分は以下に書かれています

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 を取得し、それを 2 番目のテーブルに挿入する必要があります。

生成された ID を取得するには、新しいJDBC 3.0メソッドを使用できます。getGeneratedKeys()一方、PreparedStatementSQL インジェクションを回避するために使用する必要があります。

 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-get generatedkeysを参照してください。

于 2012-05-18T06:04:58.243 に答える