Chapter Objectives
- ADO.NET Architecture
- Connection class
- Command and Data Reader Class
- DataAdapter and DataTable class
- DataSet class
- Provider Agnostic code
ADO.NET Architecture
- Connection-based: They are the data provider objects such as Connection, Command, DataAdapter and DataReader. They execute SQL statements and connect to a database.
- Content-based: They are found in the System.Data namespace and includes DataSet, DataColumn, DataRow and DataRelation. They are completely independent of the type of data source.
ADO.NET Namespaces
| Namespaces | Description |
| System.Data | Contains the definition of columns, relations, tables, database, rows, views, and constraints. |
| System.Data.SqlClient | Contains the classes that used to connect to a Microsoft SQL Server database such as SqlCommand, SqlConnection, SqlDataAdapter. |
| System.Data.Odbc | Contains classes required to connect to most ODBC drivers. These classes include OdbcCommand, OdbcConnection. |
| System.Data.OracleClient | Contains classes such as OracleConnection, OracleCommand required to connect to an Oracle database. |
Table 1.1 ADO.NET Namespace
You need to establish a connection class object for inserting, updating, deleting and retrieving data from a database. The Connection class allows you to establish a connection to the data source. The Connection class object needs the necessary information to discover the data source and this information is provided by a connection string.
You need to supply a connection string in the Connection class object. The connection string is a series of name/value settings separated by semicolons (;). A connection string requires a few pieces of information, such as the location of the database, the database name, and the database authentication mechanism.
This connection is used to connect to the Master database on the current computer using integrated security (indicated currently logged-in Windows user to access the database).
C# Code
Connection Class
Connection Strings
- string conString = "Data Source=localhost;Initial Catalog=Master;Integrated Security=SSPI";
- string conString = "Data Source=localhost;Database=Master;user id=sa;password=sa";
- string conString = "Data Source=localhost;Initial Catalog=Master;user id=sa;password=;Provider=MSDAORA";
- <configuration>
- <connectionStrings>
- <add name="Master" connectionString ="Data Source=localhost;Initial Catalog=Master;Integrated Security=SSPI" />
- </connectionStrings>
- </configuration>
- string conSting = ConfigurationManager.ConnectionStrings["Master"].ConnectionString ;
- SqlConnection Conn = new SqlConnection(conSting);
Testing a Connection
- private void Form1_Load(object sender, EventArgs e)
- {
- string conSting = ConfigurationManager.ConnectionStrings["Master"].ConnectionString ;
- SqlConnection Conn = new SqlConnection(conSting);
- try
- {
- Conn.Open();
- textBox1.Text = "Server Version=" + Conn.ServerVersion;
- textBox1.Text += "Connection Is=" + Conn.State.ToString();
- }
- catch (Exception err)
- {
- textBox1.Text = err.Message;
- }
- finally
- {
- Conn.Close();
- textBox1.Text += "Connection Is=" + Conn.State.ToString();
- }
- }
- SqlConnectionStringBuilder obj = new SqlConnectionStringBuilder();
- obj.DataSource = "localhost";
- obj.InitialCatalog = "Master";
- obj.IntegratedSecurity = true;
- SqlConnection Conn = new SqlConnection(obj.ConnectionString);
Command and Data Reader Classes
- //Command Class definition
- SqlCommand sc = new SqlCommand();
- sc.Connection = Conn;
- sc.CommandType = CommandType.Text;
- sc.CommandText = query;
- //Command Class definition
- SqlCommand sc = new SqlCommand(query,Conn);
- private void Form1_Load(object sender, EventArgs e)
- {
- //Connection String
- SqlConnectionStringBuilder obj = new SqlConnectionStringBuilder();
- obj.DataSource = "localhost";
- obj.InitialCatalog = "AdventureWorksLT2008";
- obj.IntegratedSecurity = true;
- // Add Connection string to SqlConnection
- SqlConnection Conn = new SqlConnection(obj.ConnectionString);
- // Query to retrieve records from AdventureWorks Database
- string query = "select FirstName,LastName from SalesLT.Customer";
- //Command Class definition
- SqlCommand sc = new SqlCommand();
- sc.Connection = Conn;
- sc.CommandType = CommandType.Text;
- sc.CommandText = query;
- SqlDataReader sdr = null;
- try
- {
- //Open connection
- Conn.Open();
- sdr = sc.ExecuteReader();
- //Get all records
- while(sdr.Read())
- {
- textBox1.AppendText(sdr.GetValue(0) + "\t" + sdr.GetValue(1));
- textBox1.AppendText("\n");
- }
- }
- catch (Exception err)
- {
- textBox1.Text = err.Message;
- }
- finally
- {
- //Release reader and connection object
- sdr.Close();
- Conn.Close();
- }
- }
- //Automatically releasing the Reader class Object
- sdr = sc.ExecuteReader(CommandBehavior.CloseConnection);
DataReader Class
DataReader with ExecuteReader() Method
- //Open connection
- Conn.Open();
- sdr = sc.ExecuteReader(CommandBehavior.CloseConnection);
- //Get all records
- while(sdr.Read())
- {
- textBox1.AppendText(sdr.GetValue(0) + "\t" + sdr.GetValue(1));
- textBox1.AppendText("\n");
- }
ExecuteScalar() Method
- private void Form1_Load(object sender, EventArgs e)
- {
- //Connection String
- string conString = @"Data Source=localhost;Database=AdventureWorksLT2008;Integrated Security=SSPI";
- // Add Connection string to SqlConnection
- SqlConnection Conn = new SqlConnection(conString);
- // Query to retrieve records from AdventureWorks Database
- string query = "select COUNT(*) from SalesLT.Customer";
- //Command Class definition
- SqlCommand sc = new SqlCommand(query, Conn);
- //Open connection
- Conn.Open();
- int CountCustomer = (int)sc.ExecuteScalar();
- //Count all records
- textBox1.AppendText("Total Customer=\t" + CountCustomer.ToString());
- }
ExecuteNonQuery() Method
- private void Form1_Load(object sender, EventArgs e)
- {
- //Connection String
- string conString = @"Data Source=localhost;Database=AdventureWorksLT2008;Integrated Security=SSPI";
- // Add Connection string to SqlConnection
- SqlConnection Conn = new SqlConnection(conString);
- // Query to retrieve records from AdventureWorks Database
- string query = @"update AdventureWorksLT2008.SalesLT.Customer
- set FirstName='ajay'
- where CustomerID=2";
- //Command Class definition
- SqlCommand sc = new SqlCommand(query, Conn);
- //Open connection
- Conn.Open();
- //Reflect changes into database
- int CountCustomer = sc.ExecuteNonQuery();
- //Result
- MessageBox.Show("Record Update Successfully");
- }
DataAdapter and DataTable class
- private void Form1_Load(object sender, EventArgs e)
- {
- //Connection String
- string conString = "Data Source=localhost;Database=AdventureWorksLT2008;Integrated Security=SSPI";
- // Add Connection string to SqlConnection
- SqlConnection Conn = new SqlConnection(conString);
- // Query to retrieve records from AdventureWorks Database
- string query = "select FirstName,LastName from SalesLT.Customer";
- //Command Class definition
- SqlCommand sc = new SqlCommand(query, Conn);
- // Data Adapter definition
- SqlDataAdapter sda = new SqlDataAdapter(sc);
- // filling the result set in data table
- DataTable dt = new DataTable();
- sda.Fill(dt);
- //output in data grid
- dataGridView1.DataSource = dt.DefaultView;
- }
| Property | Description |
| SelectCommand | This command executed to fill in a Data Table with the result set. |
| InsertCommand | Executed to insert a new row to the SQL database. |
| UpdateCommand | Executed to update an existing record on the SQL database. |
| DeleteCommand | Executed to delete an existing record on the SQL database. |
Table 1.2 Data Adapter Properties
C# Code
SelectCommand Example
- ..
- // Query to retrieve records from AdventureWorks Database
- string query = "select FirstName,LastName from SalesLT.Customer";
- //Command Class definition
- SqlCommand sc = new SqlCommand(query, Conn);
- // Data Adapter definition
- SqlDataAdapter sda = new SqlDataAdapter();
- sda.SelectCommand = sc;
- // filling the result set in data table
- DataTable dt = new DataTable();
- sda.Fill(dt);
- ..
Update Command Example
- ..
- string query = @"update AdventureWorksLT2008.SalesLT.Customer
- set FirstName='ajay'
- where CustomerID=2";
- //Command Class definition
- SqlCommand sc = new SqlCommand(query, Conn);
- // Data Adapter definition
- SqlDataAdapter sda = new SqlDataAdapter();
- sda.UpdateCommand = sc;
- ..
Parameterized Commands (Stored Procedure)
- Create Proc GetCustomer
- @CustID varchar(10)
- AS
- select * from SalesLT.Customer where CustomerID=@CustID
- GO
- private void btnData_Click(object sender, EventArgs e)
- {
- //Connection String
- string conString = "Data Source=localhost;Database=AdventureWorksLT2008;Integrated Security=SSPI";
- // Add Connection string to SqlConnection
- SqlConnection Conn = new SqlConnection(conString);
- //Command Class definition
- SqlCommand sc = new SqlCommand("GetCustomer", Conn);
- sc.CommandType = CommandType.StoredProcedure;
- sc.Parameters.Add("@CustID",txtParameter.Text);
- // Data Adapter definition
- SqlDataAdapter sda = new SqlDataAdapter(sc);
- // filling the result set in data table
- DataTable dt = new DataTable();
- sda.Fill(dt);
- //output in data grid
- dataGridView1.DataSource = dt.DefaultView;
- }

DataSet class
- private void Form1_Load(object sender, EventArgs e)
- {
- //Connection String
- string conString = "Data Source=localhost;Database=AdventureWorksLT2008;Integrated Security=SSPI";
- // Add Connection string to SqlConnection
- SqlConnection Conn = new SqlConnection(conString);
- string query = "select * from SalesLT.Customer";
- //Command Class definition
- SqlCommand sc = new SqlCommand(query, Conn);
- // Data Adapter definition
- SqlDataAdapter sda = new SqlDataAdapter();
- sda.SelectCommand = sc;
- //data Set definition
- DataSet ds = new DataSet();
- // filling the result set in data table
- sda.Fill(ds, "SalesLT.Customer");
- //output in data grid
- dataGridView1.DataSource = ds.Tables["SalesLT.Customer"];
- }

Provider Agnostic code
- <?xml version="1.0" encoding="utf-8" ?>
- <configuration>
- <connectionStrings>
- <add name="Adventure" connectionString ="Data Source=localhost;Database=AdventureWorksLT2008;Integrated Security=SSPI" />
- </connectionStrings>
- <appSettings>
- <add key ="factory" value="System.Data.SqlClient" />
- <add key="CustQuery" value ="select * from SalesLT.Customer"/>
- </appSettings>
- </configuration>
- private void Form1_Load(object sender, EventArgs e)
- {
- //Get the Factory
- string factory = ConfigurationManager.AppSettings["factory"];
- DbProviderFactory pro = DbProviderFactories.GetFactory(factory);
- //Use this factory to create a connection
- DbConnection con = pro.CreateConnection();
- con.ConnectionString = ConfigurationManager.ConnectionStrings["Adventure"].ConnectionString;
- //Create the command
- DbCommand cmd = pro.CreateCommand();
- cmd.CommandText = ConfigurationManager.AppSettings["CustQuery"];
- cmd.Connection = con;
- //Open the connection
- con.Open();
- DbDataReader rdr = cmd.ExecuteReader();
- //Get all records
- while (rdr.Read())
- {
- textBox1.AppendText(rdr.GetValue(3) + "\t" + rdr.GetValue(5));
- textBox1.AppendText("\n");
- }
- }

Gowtham RajamanickamPosted Apr 12, 2016, 2:27 AM
nice share
Krishna Rajput SinghPosted Dec 10, 2014, 4:04 PM
nce article helpful
Ajay YadavPosted Dec 9, 2014, 10:47 PM
Thank you
Ramesh BabuPosted Dec 9, 2014, 8:38 AM
Very nice article..
Manish Kumar ChoudharyPosted Dec 9, 2014, 5:15 AM
Nice one Ajay Yadav sir..