Skip to content

Instantly share code, notes, and snippets.

@luisdeol
Created July 8, 2020 00:11
Show Gist options
  • Save luisdeol/8a77a481b78b21f062e565ac1b7efffd to your computer and use it in GitHub Desktop.
Save luisdeol/8a77a481b78b21f062e565ac1b7efffd to your computer and use it in GitHub Desktop.
4.2: Using transactions with SqlConnection and SqlCommand.
using System;
using System.Data.SqlClient;
using System.Transactions;
namespace _42_ConsumeData
{
class Program
{
static void Main(string[] args)
{
const string connectionString = "Server=LAPTOP-201QPF8A\\SQLEXPRESS;Database=EcommerceDb;Trusted_Connection=true";
const string productDescription = "Product 4";
const int productQuantity = 400;
const decimal productPrice = 400.0m;
using (var transactionScope = new TransactionScope())
{
using (var sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
const string insertionQuery = "INSERT INTO Product VALUES (@description, @quantity, @price)";
// Setting and running INSERT command
var sqlCommand = new SqlCommand(insertionQuery, sqlConnection);
sqlCommand.Parameters.Clear();
sqlCommand.Parameters.AddWithValue("description", productDescription);
sqlCommand.Parameters.AddWithValue("quantity", productQuantity);
sqlCommand.Parameters.AddWithValue("price", productPrice);
sqlCommand.ExecuteNonQuery();
transactionScope.Complete(); // If you comment this line, you will notice that the insertion is not completed.
}
}
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment