Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
Like this article? We recommend


The Connection is the gatekeeper to working with a data source. It has operations for opening a connection or starting and committing a local transaction, as well as a creation function to use in creating a command object to work with the data source.

The first example in Listing 1 illustrates how to insert a row into the Customers table of the Northwind database.

Listing 1 SQL Provider Insert Demo

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;

namespace ConnectedOpsDemo

class SqlCmdInsertDemo

static void Main(string[] args)
   SqlConnection conn = null;
   SqlTransaction txn = null;

     // open connection to the data source
     conn = new SqlConnection(
      "server=(local);database=Northwind;" +
      "integrated security=true;");

     // begin a local transaction with isolation level of
     txn = conn.BeginTransaction(IsolationLevel.Serializable);

     // associate the command object with the connection and
     // transaction along with setting the SQL command to execute
     SqlCommand cmd = new SqlCommand();
     cmd.Connection = conn;
     cmd.Transaction = txn;
     cmd.CommandType = CommandType.Text;
     cmd.CommandText = "INSERT INTO Customers VALUES" +
        "('DALEM','Microsoft','Dale Michalk','ADC'," +
        "'101 Main Street', 'Charlotte', 'NC', '28222'," +

     int rows = cmd.ExecuteNonQuery();

     Console.WriteLine("INSERT Executed with {0} rows affected.",

     // if we reach this point...we should commit the local
   catch (SqlException se)
     Console.WriteLine("INSERT Failed with SQL Exception: {0}"

     // rollback the local transaction with a SQL Exception problem
     if (txn != null)
     // close the connection in the face of exceptions
     if (conn != null)

We start by creating the Connection object and passing in a connection string to the Northwind database. The next step is opening the configured connection and creating a local transaction using the BeginTransaction method of the Connection object. The isolation level of the transaction is configurable; in this example we use Serializable to ensure the highest level of consistency.

  • + Share This
  • 🔖 Save To Your Account