Reputation: 196489
What is the best way to put transactionality around the following C# db read code accessing a MySQL db below. And maybe the more important question is "is there any need to ever put transactionality around single read statements"
public List<Item> RunQuery(DateTime runDate)
{
var connection = new MySqlConnection(CONNECTION_STRING);
connection.Open();
string query = "select * from MyTable order by name";
var cmd = new MySqlCommand(query, connection);
MySqlDataReader myReader = cmd.ExecuteReader();
var items = new List<Item>();
try
{
while (myReader.Read())
{
items.Add(new Item
{
Name = myReader.GetString("name"),
Date = myReader.GetDateTime("date")
});
}
}
finally
{
myReader.Close();
connection.Close();
}
return items;
}
Upvotes: 0
Views: 74
Reputation: 5092
As Nitin Midha mentioned, there is no need to use a transaction when you only read data, or even if your code updates data but with only one database access (i.e., calling a SP that does the insert, update and or delete for you). Having said that, Transactions should be as atomic as possible, so they should be created immmediately before the first database update access and immediately after the last one. If it's inside a try catch block, you can define de transaction variable before the try, then open it when needed inside the try, then in the catch section ask if transaction != null and if so then rollback. The commit would be in the try block.
For instance:
DbTransaction tx = null;
try
{
tx = Connection.CreateTransaction();
Connection.ExecuteNonQuery(tx, "SPNameOrSQLInstruction", new object[] { param1, param2 });
tx.Commit();
}
catch (Exception ex)
{
if(tx != null)
tx.Rollback();
Logger.Log (ex);
}
Upvotes: 2