Ram
Ram

Reputation: 49

What is the Effective way of Accessing sql database in asp.net

In asp.net webform projects we create a connection channel where ever we need to access(insert,update,delete,select) the database which is like more or less as below mentioned.

My thought about this is can we create a class which stores all the queries and the connection string.is this way is correct ? if not what is the professional way ?

public bool ValidateFunc(string findText, string findField)//checking whether the mailid or username already exits
        {
            .. .. 
            .. ..
            string connstr = ConfigurationManager.ConnectionStrings["Connectionstr"].ConnectionString;
            SqlConnection Connection = new SqlConnection(connstr);
            string seletquery = @"SELECT * FROM Registration WHERE" + findField + "  = @Findt";
            SqlCommand Command = new SqlCommand(seletquery, Connection);
            Command.Parameters.AddWithValue("@Findt", findText);
            Connection.Open();
            SqlDataReader ad = Command.ExecuteReader();
            .. ..
            .. ..    
        }


public void InsertFunc()//inserting into database 
        {
            string connstr = ConfigurationManager.ConnectionStrings["Connectionstr"].ConnectionString;
            SqlConnection Connection = new SqlConnection(connstr);
            string insertq = @"insert into Registration values (@fname,@lname,@dob,@emailid,@uname)";
            SqlCommand Command = new SqlCommand(insertq, Connection);
            Connection.Open();
            Command.ExecuteNonQuery();
            Connection.Close();

        }

Upvotes: 2

Views: 109

Answers (1)

rsbarro
rsbarro

Reputation: 27349

I would not bundle all DB access into a single class. As your project grows, it will quickly become unmanageable.

One way to go that is widely accepted is to use the Repository pattern.

See this StackOverflow question for more information: Repository Pattern Step by Step Explanation

This writeup on MSDN is also pretty good: http://msdn.microsoft.com/en-us/library/ff649690.aspx

Upvotes: 2

Related Questions