The SqlConnection BeginTransaction is a method in the System.Data.SqlClient library of C# that begins a transaction on a SQL Server connection.
Example 1:
SqlConnection conn = new SqlConnection(connectionString); conn.Open(); SqlTransaction tran = conn.BeginTransaction(); SqlCommand cmd1 = new SqlCommand("INSERT INTO tableName (col1, col2) VALUES (@val1, @val2)", conn, tran);
In this example, we create a new SqlConnection object and open it with a specified connection string. Then, we begin a new transaction using the BeginTransaction method and assign it to a SqlTransaction object. Finally, we create a new SqlCommand object with a SQL statement to insert data into a table, passing the SqlConnection and SqlTransaction objects as parameters.
Example 2: SqlConnection conn = new SqlConnection(connectionString); conn.Open(); SqlTransaction tran = conn.BeginTransaction(IsolationLevel.Serializable); SqlCommand cmd1 = new SqlCommand("DELETE FROM tableName WHERE col1 = @val1", conn, tran);
In this example, we specify a transaction isolation level of Serializable when beginning the transaction. This ensures that the data read by the transaction is locked until the transaction is completed, preventing other transactions from modifying the data. We then create a SqlCommand object with a SQL statement to delete data from a table.
Both examples use the System.Data.SqlClient package library in C#.
C# (CSharp) System.Data.SqlClient SqlConnection.BeginTransaction - 60 examples found. These are the top rated real world C# (CSharp) examples of System.Data.SqlClient.SqlConnection.BeginTransaction extracted from open source projects. You can rate examples to help us improve the quality of examples.