Below is my table in which ID column is Primary Key. And other two columns are string.
I am using a new Database named XpressMP.
Column Name
-------
ID PrimaryKey
SEARCHES String
ACCOUNT String
I am trying to achieve functionality of UPSERT here-
If ID doesn't exists here then insert a new record.
And ID exists then update the record.
I know If I am working with Oracle then I can use MERGE sql command but MERGE is not supported in that database and there is no other command for that as of now. But I believe I can do the same thing with Stored Procedure.
Can anyone provide some suggestions how can I do the same thing with Stored Procedure? As stored procedure will work there.
UPDATED:-
public final static String INSERT = "BEGIN"
+" INSERT INTO TABLE (ID, SEARCHES, ACCOUNT) VALUES (?, ?, ?)"
+" EXCEPTION"
+" WHEN DUP_VAL_ON_INDEX THEN"
+" UPDATE TABLE"
+" SET SEARCHES = ?, ACCOUNT = ?"
+" WHERE ID = ?"
+" END";
Whenever I try to execute the above stored procedure like this
preparedStatement = dbConnection.prepareStatement(INSERT);
preparedStatement.setString(1, String.valueOf(userId));
preparedStatement.setString(2, Constants.getaAccount(userId));
preparedStatement.setString(3, Constants.getaAdvertising(userId));
preparedStatement.executeUpdate();
I get exception? Is this the right way to execute it?
You can handle it using the
DUP_VAL_ON_INDEXexception.You can add the below code in your procedure, which should meet your requirement.
You can read more about DUP_VAL_ON_INDEX Exception here and here.
Another option would be to insert or update the data after checking the count.