Provider Agonostic Code

BangaruBabu
Posted by BangaruBabu under ASP.NET category on | Views : 2010
protected void btnSubmit_Click(object sender, EventArgs e)
{

try
{

//Getting Provider Name & Connection String From Web.Config File

string providerName = ConfigurationManager.ConnectionStrings["GenericDBConnectionString"].ProviderName;

string ConString = ConfigurationManager.ConnectionStrings["GenericDBConnectionString"].ConnectionString;

//Step-1: Create Factory object

DbProviderFactory facObj = DbProviderFactories.GetFactory(providerName);

//Step-2: Create Connection For Factory

DbConnection cn = facObj.CreateConnection();

//Step-3: Assign Connection String To Connection Object

cn.ConnectionString = ConString;

//Step-4: Create Command For Database Manipulations with ConnectionString

DbCommand cmd = cn.CreateCommand();

//Step-5: Bind The Properties For Command Object

cmd.CommandType = CommandType.Text;

cmd.CommandText = "insert into tbl_profile(Name,PhoneNo,Address)values('" + txtname.Text + "','" + txtphoneno.Text + "','" + txtaddress.Text + "')";

//Step-6: Open Connection -> Execute Query -> Close Connection

cn.Open();

cmd.ExecuteNonQuery();

cn.Close();

Page.ClientScript.RegisterStartupScript(typeof(string), "popupalert", "<script>alert('Profile Created Successfully')</script>");

}

catch (Exception ex)
{

Page.ClientScript.RegisterStartupScript(typeof(string), "popupalert", "<script>alert('" + ex.Message + "')</script>");
}
}


Web.Config
------------
view source
print?
<connectionStrings>
<add name="GenericDBConnectionString" connectionString="Data Source=BANGARUBABU;Initial Catalog=GenericDB;User ID=sa;Password=123" providerName="System.Data.SqlClient" />
</connectionStrings>

Comments or Responses

Login to post response