* 参照設定を右クリックし[参照の追加]-[.NET]で「System.Transactions」を選択する
* 「using System.Transactions;」を追加する
■ サンプル
using System.Transactions;
// 中略
private void button1_Click(object sender, EventArgs e)
{
this.InsertData();
}
private void InsertData()
{
var connectionString =
System.Configuration.ConfigurationManager.ConnectionStrings[
"Xxxxx.SampleDBConnectionString"].ConnectionString;
using (var scope = new TransactionScope())
using (var sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
using (var command = sqlConnection.CreateCommand())
{
command.CommandText =
"INSERT INTO Person(Name, Address, Email, Age) VALUES(@Name, @Address, @Email, @Age)";
this.SetDbParameter(command, "@Name", "Mike");
this.SetDbParameter(command, "@Address", "1-23-4 NY USA");
this.SetDbParameter(command, "@Email", "xxx@xxx.com");
this.SetDbParameter(command, "@Age", 23);
command.ExecuteNonQuery();
// コミット
scope.Complete();
}
sqlConnection.Close();
}
}
private void SetDbParameter(
SqlCommand command,
string parameterName,
object value)
{
var parameter = command.CreateParameter();
parameter.ParameterName = parameterName;
parameter.Value = value;
command.Parameters.Add(parameter);
}