DbProviderFactory: create provider from SqlClient : DbProviderFactory « ADO.net Database « ASP.NET Tutorial






<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="ProviderAgnosticCode" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
          <h2>Employees</h2>
    <asp:Literal runat="server" ID="HtmlContent" />
    </div>
    </form>
</body>
</html>

File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.Common;
using System.Text;
using System.Web.Configuration;

public partial class ProviderAgnosticCode : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    string factory = WebConfigurationManager.AppSettings["factory"];
    DbProviderFactory provider = DbProviderFactories.GetFactory(factory);

    DbConnection con = provider.CreateConnection();
    con.ConnectionString = WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
    
    DbCommand cmd = provider.CreateCommand();
    cmd.CommandText = WebConfigurationManager.AppSettings["employeeQuery"];
    cmd.Connection = con;

    con.Open();
    DbDataReader reader = cmd.ExecuteReader();

    StringBuilder htmlStr = new StringBuilder("");
    while (reader.Read())
    {
      htmlStr.Append("<li>");
      htmlStr.Append(reader["TitleOfCourtesy"]);
      htmlStr.Append(" <b>");
      htmlStr.Append(reader.GetString(1));
      htmlStr.Append("</b>, ");
      htmlStr.Append(reader.GetString(2));
      htmlStr.Append(" - employee from ");
      htmlStr.Append(reader.GetDateTime(6).ToString("d"));
      htmlStr.Append("</li>");
    }

    reader.Close();
    con.Close();

    HtmlContent.Text = htmlStr.ToString();
    }
}

File: Web.config

<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
  <connectionStrings>
    <add name="Northwind" connectionString="Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI"/>
  </connectionStrings>

  <appSettings>
    <add key="factory" value="System.Data.SqlClient" />
    <add key="employeeQuery" value="SELECT * FROM Employees" />
  </appSettings>

  <system.web>
    <compilation debug="true"/>
    <authentication mode="Windows"/>
  </system.web>
</configuration>








18.35.DbProviderFactory
18.35.1.DbProviderFactory: create provider from SqlClient