I'm doing a transaction with OleDb. I don't show how did I calculate the variables like finalQuantity
and finalMoneyBuyer
because it's not important. My code is this:
using(OleDbConnection con = DAL.GetConnection())
{
OleDbTransaction transaction = null;
try
{
con.Open();
transaction = con.BeginTransaction();
if (realQuantity == quantity)
{
sql = "DELETE FROM item WHERE (id =" + id + ")";
}
else if (realQuantity > quantity)
{
sql = "UPDATE item SET quantity = " + finalQuantity + " WHERE (id = "+id+")";
}
OleDbCommand cmd = DAL.GetCommand(con, sql);
cmd.Transaction = transaction;
string sql2 = "UPDATE lol SET money = " + finalMoneyBuyer + " WHERE (UserName = '" + Session["username"] + "')";
OleDbCommand cmd2 = DAL.GetCommand(con, sql2);
cmd2.Transaction = transaction;
string sql3 = "UPDATE lol SET money = " + finalMoneySeller + " WHERE (UserName = '" + seller + "')";
OleDbCommand cmd3 = DAL.GetCommand(con, sql3);
cmd3.Transaction = transaction;
int num1 = cmd.ExecuteNonQuery();
int num2 = cmd2.ExecuteNonQuery();
int num3 = cmd3.ExecuteNonQuery();
if(num1 == 0 || num2 == 0 || num3 == 0)
{
//No esperamos a que sea 0, asi que vamos a echar para atras todo lo que hicimos
transaction.Rollback();
//mandar error
Response.Redirect("home.aspx?err=Error1");
}
else
{
transaction.Commit();
Response.Redirect("home.aspx?err=Purchase was successful!");
}
}
catch(OleDbException ex)
{
try
{
//algo malo paso, vamos a echar para atras todo lo que hicimos.
transaction.Rollback();
Response.Redirect("home.aspx?err=Error2");
}
catch{}
}
}
After running the code... I get this error:
I hope you can help, thanks.
You have to set the transaction for the command objects:
etc.