using (SqlConnection con = new SqlConnection(connectionString)) { con.Open(); string queryString = "SELECT * FROM Customers"; SqlCommand command = new SqlCommand(queryString, con); SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection | CommandBehavior.SequentialAccess); while (reader.Read()) { Console.WriteLine("ID: {0}, Name: {1}", reader["CustomerId"], reader["Name"]); } }
using (SqlConnection con = new SqlConnection(connectionString)) { con.Open(); SqlCommand command = new SqlCommand("INSERT INTO Customers (Name, Address) VALUES ('John Smith', '123 Main St')"); command.Connection = con; SqlTransaction transaction = con.BeginTransaction(); command.Transaction = transaction; int rowsAffected = command.ExecuteNonQuery(CommandBehavior.Default); if (rowsAffected > 0) { Console.WriteLine("Data has been added to the database."); } else { Console.WriteLine("Data has not been added to the database."); } transaction.Commit(); }This code example shows CommandBehavior.Default being used to execute a non-query operation with a transaction. It creates a new SQL transaction, assigns it to the command object, and then commits it upon successful execution of the command. Package library: The CommandBehavior enumeration is part of the System.Data.SqlClient namespace, which is included in the Microsoft .NET Framework Class Library. Therefore, no package is required to use this feature as it is natively available in the .NET Framework.