Friday, March 23, 2012

Please explain Transaction for me

I found this on http://msdn2.microsoft.com/en-us/library/86773566.aspx which i am hoping may be able to resolve my problem but I am not sure I actually understand it.

Where it shows

// Start a local transaction.
transaction = connection.BeginTransaction("SampleTransaction");

is the "SampleTransaction" nothing more then just a name of the transaction that is being created through this code or is it actually pointing to something?

I believe that I understand the rest.

Oh and in case you have a better way of doing what I am needing here is the SQL Query that is pulling info for me to display on a page

SELECT p.product_ID, p.class_ID, p.category_ID, p.product_name, p.product_desc, p.product_image, p.product_dimension, p.product_o1, p.product_o2,
p.product_o3, p.product_ac, p.product_ph, p.product_photo, pcl.class_name, pca.category_name
FROM products AS p INNER JOIN
productClass AS pcl ON p.class_ID = pcl.class_ID INNER JOIN
productCategories AS pca ON p.category_ID = pca.category_ID

Basically I am using the transaction to perform multiple updates seeing as how I will need to update multiple tables.

privatestaticvoid ExecuteSqlTransaction(string connectionString)
{
using (SqlConnection connection =new SqlConnection(connectionString))
{
connection.Open();

SqlCommand command = connection.CreateCommand();
SqlTransaction transaction;

// Start a local transaction.
transaction = connection.BeginTransaction("SampleTransaction");

// Must assign both transaction object and connection
// to Command object for a pending local transaction
command.Connection = connection;
command.Transaction = transaction;

try
{
command.CommandText =
"Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
command.ExecuteNonQuery();
command.CommandText =
"Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
command.ExecuteNonQuery();

// Attempt to commit the transaction.
transaction.Commit();
Console.WriteLine("Both records are written to database.");
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);

// Attempt to roll back the transaction.
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
// This catch block will handle any errors that may have occurred
// on the server that would cause the rollback to fail, such as
// a closed connection.
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
}
}
}
}

It's a name given to the transaction to be used in RollBack and SavePoint

SqlTransaction.Rollback (String)

Save method.

Read this inRemarksection atMSDNhttp://msdn2.microsoft.com/en-us/library/k1562zz1.aspx

sql

No comments:

Post a Comment