Embedding SQL in ASP.NET


There are several ways to embed SQL statements in an ASP.NET program. Three of them are discussed next:
  1. ADO.NET (ActiveX Data Objects),
  2. SqlDataSource control, and
  3. AccessDataSource control.
ADO.NET (to be discussed in Slides 10)
ADO.NET is a data access technology from the Microsoft .NET framework which provides communication between relational and non-relational systems through a common set of components. The ADO.NET code you would normally write in a page includes the following tasks, for example:
  1. Connect to an Access database,
  2. Compose and execute an SQL statement, and
  3. Bind the SQL result set to a control, e.g., author.
using System;
using System.Data.OleDb;

public partial class NextPage : System.Web.UI.Page {
 protected void List_SelectedIndexChanged( object sender, EventArgs e ) {
  OleDbConnection conn = new OleDbConnection(
    @"Provider=Microsoft.ACE.OleDb.12.0;Data Source=" +
    Server.MapPath( "Access\\bookstore.accdb" ) );
  String sql = "SELECT authorID, authorName, email ";
  sql += "FROM authors WHERE authorName = @authorName";
  OleDbCommand cmd = new OleDbCommand( sql, conn );
  cmd.Parameters.AddWithValue( "@authorName", authorList.SelectedValue );
  conn.Open( );
  var dbread = cmd.ExecuteReader( );
  author.DataSource = dbread;
  author.DataBind( );
  dbread.Close( );
  conn.Close( );
 }
}