Thursday, March 15, 2007

Simplest Way to perform Database operations in ASP.NET

This is the simplest way to perform Database operation using C#.NET for beginners.
This function just give you the step by step explanation to perform the database operations. However the best way to perform db operations is to build a business logic and dbOperations layer seperately but for beginners who wants to know how to perform database operations this is the best approach to learn.


private void SaveDataToDB() // Function to perform db operation
{
/* Putting your connection string inside web.config will make the easy transportation of your code without recompilation. you just need to write your connection string once and use it through out your project. Also changing the connection string doesn't need the code compilation however if you will put your connection code in CS file (in the code) you need to recompile the code each time you will migrate from one server to another.
*/

/* Reading Connection String from your configuration settings */
string conn = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"].ToString();
/*
Or you can specify your connection string directly here.
*/
string query = @"insert into TABLE_BASIC_INFO
(LAST_NAME, FIRST_NAME, EMAIL_ID, NO_OF_CORRECT_ANS, DATE_OF_TEST)
values ('" + tbLastName.Text + "', '" + tbFirstName.Text + "', '" + tbEmailID.Text + "', " +
int.Parse(Session["ScoreQuestionDetail"].ToString())+ ",'" + System.DateTime.Now.ToShortDateString () + "')";

SqlConnection mySqlConnection = new SqlConnection(conn); // New SQLConnection Object
SqlCommand sqlComm = new SqlCommand(query, mySqlConnection);
try
{
mySqlConnection.Open ();
sqlComm.ExecuteNonQuery(); // Performing query to the database
mySqlConnection.Close();
}
catch (SqlException se)
{
Response.Write("Currently Facing Problem with Server " + "
" + se.ToString());
}

// Response.Write("Somewhat Problem with dbOperation "+se.ToString());
}