Click here to Skip to main content
15,895,709 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
i can't get 2 query
just working string query
and query dont


C#
      internal bool saveNewPayment(Guid ID, Guid creditID, decimal paymentAmount, DateTime dateTime)
      {
          bool flag = true;
          using (SqlConnection con = new SqlConnection(constring))
          {
              con.Open();
              SqlTransaction sqlTranc = con.BeginTransaction();
              SqlCommand com = con.CreateCommand();
              com.Transaction = sqlTranc;

              try
              {
                  string payAmount = paymentAmount.ToString(CultureInfo.InvariantCulture.NumberFormat);


                 string query = string.Format("INSERT INTO Payment (ID, CreditsID, Amount, PaymenDate)" + " VALUES ('{0}', '{1}', '{2}', '{3}')",
                   ID, creditID, payAmount, dateTime.ToString("MM/dd/yyyy"));

                  com.CommandText = query;
                  com.ExecuteNonQuery();

                 query = string.Format("UPDATE Credits SET Balance = (Balance - {0}) WHERE ID = '{1}'", payAmount, creditID);

                  com.CommandText = query;
                  com.ExecuteNonQuery();


                  sqlTranc.Commit();

              }
              catch (Exception)
              {
                  sqlTranc.Rollback();
                  flag = false;
              }
              finally
              {
                  if (con.State == System.Data.ConnectionState.Open)
                      con.Dispose();
              }
          }
          return flag;

      }
  }
}
Posted
Comments
Herman<T>.Instance 28-Nov-12 18:28pm    
you do 2 commands over 1 statement. Second query will not work if it is first one. Than no entry in table.
Adam R Harris 11-Dec-12 15:18pm    
What is the value of creditId?
What is the field type of ID on the Credits table?
What command isn't running?
- Does your insert run?
- Does your update run?
Rohit Shrivastava 11-Dec-12 16:53pm    
what exception is coming and on which line, did not understand the question.

1 solution

since you use the con.BeginTransaction() before the beginning of statement the real insert will not complete until you make call to sqlTranc.Commit();

so its obvious that the creditID which you are trying to update is not available in the table and it failed to update.
move the Commit statement just after the insert is completed and try running the update query.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900