Open E-School

Friday, February 24, 1984

Sample code with all CRUD operations

Category: Programming Date: Thursday, June 18, 2015

Here is a sample C# code with all the operations which you will need to perform while writing data access code using C#. I have written comments on most of the code so you should be able to understand it easily.

You can uncomment the lines of code which you want to use. The goal of providing this code is that you will get ready reference to all the code at one place.

using System;  using System.Collections.Generic;    using System.Data.SqlClient;    namespace AdoDotNetCodePractice  {      class Branch      {          public int Id;          public string BranchCode;          public string BranchName;      }        class Program      {          static void Main(string[] args)          {              // All the code we are writing here belongs to the category                // 1) Create the connection with the data                   // To perform this step we need the connection string.                   // Data Source=(local)sqlexpress;Initial Catalog=master;Integrated Security=True                SqlConnection connection = new SqlConnection();                // The connection strings should not be hard coded into your project.              // They should be kept in the App.config or web.config file              // For learning purpose we will keep our connection string in the              // source code for now.              connection.ConnectionString = @"Data Source=(local)sqlexpress;Initial Catalog=master;Integrated Security=True";                // 2) Open the connection              connection.Open();                // 3) Execute your SQL statement              SqlCommand command = new SqlCommand();              command.Connection = connection;                // Insert statement              //command.CommandText = "insert into Branches(id,branchcode,branchname) values('1','BTCS','CSE')";                // Update statement              //command.CommandText = "update Branches set branchcode='XXX',branchname='YYY' where id='1'";                // Delete statement              //command.CommandText = "delete from branches where id='1'";                // Select statement              command.CommandText = "Select * from branches";                //int rowsAffected = command.ExecuteNonQuery();                // To read the data from SQL we will be using the SQLDataReader class              SqlDataReader dr = command.ExecuteReader();                List<Branch> allBranches = new List<Branch>();              Branch branch = null;                while (dr.Read())              {                  // Inside this loop the dr is pointing to one of the rows of the table                  // Each row has multiple columns                  // We will print the value of each column in this row pointed to by the data reader                    //Console.WriteLine("Id : {0} Code : {1} Name : {2}", dr["Id"], dr["BranchCode"], dr["BranchName"] );                    // Create an object of the Branch class                  // Fill its data member values from the data reader                    branch = new Branch();                  branch.Id = Convert.ToInt32(dr["Id"]);                  branch.BranchCode = Convert.ToString(dr["BranchCode"]);                  branch.BranchName = Convert.ToString(dr["BranchName"]);                    // Add this object to the list of branches                  allBranches.Add(branch);              }                // 4) Close the connection              connection.Close();                // We will print all the data from the list using the foreach loop                foreach (Branch b in allBranches)              {                  Console.WriteLine("Id : {0} Code : {1} Name : {2}", b.Id, b.BranchCode, b.BranchName);              }            }      }  }

Rate this article and help us improve

Please Login to rate
Overall ratings: 0 | Rating: out of 5
Previous Article Next Article

Quick Links



Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..


Login to Open ESchool OR Create your account    Login   SignUp