Commonly Used C# Snippets for SQL CRUD Operations

Commonly used code snippets while in C# & SQL while reading and writing data to database.


        public void GetDataSetWithParam()
        {
            try
            {
                using (SqlConnection con = new SqlConnection(str))
                {
                    using (SqlCommand cmd = new SqlCommand("sp_GetEmpWithId", con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("Id", 1);
                        SqlDataAdapter adp = new SqlDataAdapter(cmd);
                        DataSet ds = new DataSet();
                        adp.Fill(ds);
                    }
                }
            }
            catch (Exception exp)
            {

            }
        }

        public void InsertWithParam_In_Out()
        {
            try
            {
                using(SqlConnection con=new SqlConnection(str))
                {
                    using (SqlCommand cmd = new SqlCommand("sp_InsertEmp", con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("Name", "Jayesh");

                        SqlParameter outParam = new SqlParameter("ReturnId", SqlDbType.Int,1000);
                        outParam.Direction = ParameterDirection.Output;

                        cmd.Parameters.Add(outParam);
                        con.Open();

                        cmd.ExecuteNonQuery();

                        int returnValue = (int)cmd.Parameters["ReturnId"].Value;
                    }
                }
            }
            catch (Exception exp)
            {

            }
        }


        public void GetData_UsingReader()
        {
            using (SqlConnection con = new SqlConnection(str))
            {
                using (SqlCommand cmd = new SqlCommand("sp_GetAllEmps", con))
                {
                    SqlDataReader rdr = null;
                    con.Open();
                    rdr = cmd.ExecuteReader();

                    List empList = new List();
                    Employee emp = null;
                    while (rdr.Read())
                    {
                        emp = new Employee();
                        emp.Name = rdr["Name"].ToString();
                        emp.Id = rdr["Id"].ToString();
                        empList.Add(emp);
                    }
                }
            }
        }

Post a Comment