I just wanted to know what would happen if there are multiple insert and update statements like (insert into sales(),insert into saledetails(), update sale etc.) getting executed and if any exception occurs then will be a rollback of all or the line in which the exception occurs. Below is the code.
using (var conn = new NpgsqlConnection(connstr))
{
conn.Open();
var tra = conn.BeginTransaction();
try
{
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 0;
cmd.CommandText = strQueryBuild.ToString();
RowsAffected = cmd.ExecuteNonQuery();
tra.Commit();
commitstatus = true;
}
catch (Exception ex)
{
commitstatus = false;
AppHelper.ErrrorLog(ex, "UploadFileData-Error1");
RowsAffected = -1;
tra.Rollback();
}
}
I am getting a duplicate key violation error after executing again that query.
2
Answers
As shown in the example, it only applies rollback for each operation that is performed. To rollback several operations you must start a single connection and a begintransaction for all operations.
Duplicate key error is because the query being executed is violating the
"UNIQUE" key constraint.
Temporarily, you can bypass the duplicate key error, by catching the exception and then taking a suitable action. Look for specific error code to catch duplicate key violation.
It is not a good solution, but will help temporarily.