Sunday, 12 August 2012

ASP.NET database Connection using web.config file

The simplest way to access database


When you create a Connection object, you can pass the connection string as a constructor
parameter. Alternatively, you can set the ConnectionString property by hand, as long as you do it before
you attempt to open the connection.
There’s no reason to hard-code a connection string.
The
<connectionStrings> section of the web.config file is a handy place to store your connection strings.

Example-
web.config file :-

<configuration>
<connectionStrings>
<add name="Northwind" connectionString=
"Data Source=localhost; Initial Catalog=Northwind; Integrated Security=SSPI"/>
</connectionStrings>
...
</configuration>

You can then retrieve your connection string by name from the
WebConfigurationManager.ConnectionStrings collection. Assuming you’ve imported the
System.Web.Configuration namespace, you can use a code statement like this:

public partial class _Default : System.Web.UI.Page
{
    string connectionString =
    WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString.ToString();
    protected void Page_Load(object sender, EventArgs e)
    {
            
    }
}
Declare the connection string veritable  at the class label for later user

Data Access Process from SQL Server :-

protected void InsertData()
{
       string InsertSql = "insert into Table_Name values(value1,value2.....valueN)";
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(InsertSql, con);
        int innn;
        try
        {
            con.Open();
            innn=cmd.ExecuteNonQuery();
            if (innn > 0)
            {
                Label1.Text = "Insert Successfull";
            }

        }
        catch (Exception ex)
        {
            Label1.Text = ex.Message;
        }
        finally
        {
            con.Close();
        }
}

Call this function from any Event Handler method like Button.Click[Buttion_Click(object sender, EventArgs e)] method....

This is the simple way to access database for DML or DQL execution. If you want you can get more complex execution with more security.....Like Parametrized Query and Query Builder object.......

If you need help please post your request......


No comments:

Post a Comment