This is my first article. I don't know how to explain everything but I try my best and I am hoping for good comments to motivate me.
I have noticed that Usually whenever a newbie writes C# code to access a database he/she writes the database access code multiple times for various functions like they write the complete code for each insert, update, delete and so on.
So, I am here to teach you how to make a connection class that I learned from my great and respectable teacher "Sardar Ishtiaq Ahmed". You can use that class in any project where you want to access the database.
Note: You should have knowledge of DataGridView and SqlDataReader to understand its 2 methods. The purpose of this article is to teach you all how to avoid the repitition of the database access code.
OK. Here is the step-by-step method to code the connection class.
Step 1
Import the following namespaces.
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Data.SqlClient;
- using System.Linq;
- using System.Web;
Create a namespace and a class in it:
- namespace ConnectionNamespace
- {
- public class Connection_Query
- {
- //Here put all the methods which I am defining below. . .
- }
- }
Create a varriable string for saving the connection string and a SqlConnection object:
- string ConnectionString = "";
- SqlConnection con;
Create a method to open the connecction. First I make a method OpenConnection() for accessing the database call at the very beginning to open the database connection.
- public void OpenConection()
- {
- con = new SqlConnection(ConnectionString);
- con.Open();
- }
Now create a CloseConnection method. After completing all the processes call this method to close the connection of the database that we opened in Step 4.
- public void CloseConnection()
- {
- con.Close();
- }
ExecuteQuries Method: Whenever you want to execute a query, like an insert, update or delete query then simply call this function using the object of a class and pass your query to the function.
- public void ExecuteQueries(string Query_)
- {
- SqlCommand cmd = new SqlCommand(Query_,con);
- cmd.ExecuteNonQuery();
- }
Now create a SqlDataReader Method. Learn how to use the SqlDataReader so you can understand how to use this class. Here I will explain the use of DataReader since you know my focus is the Connection class.
This function will return the data of type SqlDataReader. Make an object of SqlDataReader and call the method in it with the relevent query in it as an argument.
- public SqlDataReader DataReader(string Query_)
- {
- SqlCommand cmd = new SqlCommand(Query_,con);
- SqlDataReader dr = cmd.ExecuteReader();
- return dr;
- }
Now show the DataInGridView. As I said earlier, in the case of SqlDataReader you also should have the knowledge of the DataGridView. If you don't then learn about it so you can understant the method and its use.
It will return an object data type value as an object that is the parent of all the variables in C#.
We will initialize the datasource of the GridView with this method and a SQL Query in it as an argument.
- public object ShowDataInGridView(string Query_)
- {
- SqlDataAdapter dr = new SqlDataAdapter(Query_, ConnectionString);
- DataSet ds = new DataSet();
- dr.Fill(ds);
- object dataum = ds.Tables[0];
- return dataum;
- }
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Data.SqlClient;
- using System.Linq;
- using System.Web;
- namespace Connection_Class
- {
- public class Connection_Query
- {
- string ConnectionString = "";
- SqlConnection con;
- public void OpenConection()
- {
- con = new SqlConnection(ConnectionString);
- con.Open();
- }
- public void CloseConnection()
- {
- con.Close();
- }
- public void ExecuteQueries(string Query_)
- {
- SqlCommand cmd = new SqlCommand(Query_,con);
- cmd.ExecuteNonQuery();
- }
- public SqlDataReader DataReader(string Query_)
- {
- SqlCommand cmd = new SqlCommand(Query_,con);
- SqlDataReader dr = cmd.ExecuteReader();
- return dr;
- }
- public object ShowDataInGridView(string Query_)
- {
- SqlDataAdapter dr = new SqlDataAdapter(Query_, ConnectionString);
- DataSet ds = new DataSet();
- dr.Fill(ds);
- object dataum = ds.Tables[0];
- return dataum;
- }
- }
- }
Class Documentation
This is a class named "Connection_Class" to perform insert, update and delete and search to show the data in a DataGridView and also perform SqlDataReader operations.
Public Member Functions
- void OpenConection ()
- void CloseConnection ()
- void ExecuteQueries (string Query_)
- SqlDataReader DataReader (string Query_)
- object ShowDataInGridView (string Query_)
Member Function Documentation
- void CloseConnection ()
Call this method to close the connection.
- SqlDataReader DataReader (string Query_)
Call this method when want to show data in a TextBox or Label.
The following is the code to show how to use this method:
Parameters- SqlDataReader dr = ClassObject.DataReader("Select * From Student");
- dr.Read();
- textBox1.Text = dr["Stdnt_Name"].tostring();
Query_ : Pass the query here.
Returns
Return SqlDataReader object
- void ExecuteQueries (string Query_)
Call this method to perform insert, delete, update function.
Parameters
Query_: your required query.
- void OpenConection ()
Call this method to open the connection.
- object ShowDataInGridView (string Query_)
Call this method to show data in a DataGridView.
The following is the code to descride how to show data in GridView using it.
Parameters- dataGridView1.datasource = ClassObject.ShowDataInGridView("Select * From Student")
Query_ : Place the required query here.
Returns:
return Object with data to Show in GridView
This class was genrated by HammadMaqbool.
Note : Use it with ASP.NET and C#.


Emmanuel RangelPosted Jun 3, 2020, 6:17 AM EDT
Hi, Thanks for your help, , hoy can I use a User and Password for the connectionstring, and this class can be use for Ingres Database?
Francisco SanchezPosted Oct 30, 2019, 8:41 AM EDT
Beautiful..Thank you
Ishtiaq ahmadPosted Oct 4, 2019, 9:27 PM EDT
But a little bit confusion here while calling the code "dataGridView1.datasource = ClassObject.ShowDataInGridView("Select * From Student") " when to open the connection and close as well...
Ishtiaq ahmadPosted Oct 4, 2019, 9:26 PM EDT
Great post dear friend! it was valuable for me as well. i used it in my all projects.. Really appreciated...
Fabian LopezPosted Sep 16, 2019, 5:29 AM EDT
Can i use this on asp.net
Nikki StenskovPosted May 29, 2019, 2:43 AM EDT
How would one be able to create a login system using those?
Code AlonePosted Sep 16, 2018, 9:56 AM EDT
Your start is good. And you stopped after 1 article. Kindly continue. Explore your knowledge for needy people. Hammad Maqbool
Cheruiyot KiruiPosted Aug 4, 2018, 11:54 AM EDT
How do you execute stored procedure with parameters using this?
Hiren ModiPosted Jul 4, 2018, 3:44 AM EDT
That's what I was looking for. Thanks Brother.
Seungwon HongPosted Jun 28, 2018, 3:10 PM EDT
These days, i felt hard to write same codes to connect to DB, I'm C Sharp beginner but I found good article , here. Thank you .
jansen MalaggayPosted Jun 7, 2018, 10:41 PM EDT
Hello bro! How will i use this class windows forms like in the "Try" statement?
Naresh SinghalPosted Feb 26, 2018, 7:23 PM EST
Thanks Bhai.....for the best generic sql class..
xboy xboyPosted Jul 30, 2017, 8:02 PM EDT
Error "Object reference not set to an distance of an object" can you help me. thanks
Jack CorbettPosted Jul 24, 2015, 7:16 AM EDT
While a good start for creating a data access class, this is code that needs more work before I'd use it in a production application. Based on what you have shared it looks like the queries being executed are just built from user input. This method of query execution is wide open to SQL Injection. Any query being passed to the database should be parameterized and cleansing should be done to make sure that the query is what is expected, not something like: "Select * from table; Drop Table table"
Santhakumar MunuswamyPosted Jul 23, 2015, 10:50 AM EDT
Thanks for nice article:)
Vignesh ManiTOP 100Posted Jul 23, 2015, 4:03 AM EDT
Nice
Rajeesh MenothPosted Jul 23, 2015, 12:40 AM EDT
Good One,,check con.dispose() also
Vipul MalhotraPosted Jul 23, 2015, 12:22 AM EDT
Nice Article
Pankaj Kumar ChoudharyTOP 100Posted Jul 22, 2015, 11:21 PM EDT
Nice Start........
Sibeesh VenuTOP 100Posted Jul 22, 2015, 10:00 PM EDT
Good Information
Debasis SahaTOP 100Posted Jul 22, 2015, 8:45 PM EDT
Good one..