CRUD Operations in C#

Maleesha Wickramarathna
2 min readApr 17, 2021

In this post, I am focusing on creating SQL connection object in a better way.

step 01

In the beginning we want to create Connection. In here I am using MSSQL server as my database server. Generally we create connection string out side the program.

“In here app.config file is used to store connection string details like below screenshot”
note :- “You have to add your username and password”

we can store those details like the above screenshot. If we use this way to store connection details like this way we will be able to change our db details any time without doing any changes to the program. I think that’s why most developers tend to use this way to store connection details.

If we use this way to store connection details in app.config then we have to have a method to read values. you can see we have stored details as key-value pairs.We can get value using the key. That is the nature of key-value pairs.

step 02

Create a class, here I’m using the name as “connection.cs”.

step 03

create “SqlConnection” type object,

“private SqlConnection conn = null;”

step 04

create default constructor and initialize SQL connection object like below,

public Connection()

{

try

{

conn = new SqlConnection (ConfigurationManager.AppSettings[“connection”].ToString());

}

catch(Exception ex)

{

System.Windows.Forms.MessageBox.Show(ex.ToString());

}

--

--

Maleesha Wickramarathna

I am a 3rd-year Software Engineering undergraduate at the Sri Lanka Institute of Information Technology- SLIIT ,Reg.no :IT19004778