/// <summary> /// Add(): 입력 /// </summary> public CategoryBase Add(CategoryBase model) { SqlConnection con = new SqlConnection(); con.ConnectionString = _connectionString; con.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = con; cmd.CommandText = "Insert Into CategoryBases Values(@CategoryName);"; cmd.CommandType = CommandType.Text; //[1] SqlParameter 클래스의 인스턴스 생성 SqlParameter categoryName = new SqlParameter("@CategoryName", SqlDbType.NVarChar, 50); //[2] Value 속성으로 값 지정 categoryName.Value = model.CategoryName; //[3] 커멘트 개체에 매개 변수 추가 cmd.Parameters.Add(categoryName); cmd.ExecuteNonQuery(); con.Close(); return(model); }
/// <summary> /// Edit(): 수정 /// </summary> public bool Edit(CategoryBase model) { bool result = false; string sql = @" Update CategoryBases Set CategoryName = @CategoryName Where CategoryId = @CategoryId "; using (SqlConnection con = new SqlConnection(_connectionString)) { con.Open(); SqlCommand cmd = new SqlCommand(sql, con); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@CategoryName", model.CategoryName); cmd.Parameters.AddWithValue("@CategoryId", model.CategoryId); int count = cmd.ExecuteNonQuery(); // 영향받은 레코드 수 반환 if (count > 0) { result = true; // 업데이트 완료 } } return(result); }
/// <summary> /// Browse(): 상세 /// </summary> public CategoryBase Browse(int id) { SqlConnection con = new SqlConnection(); con.ConnectionString = _connectionString; con.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = con; cmd.CommandText = @" Select CategoryId, CategoryName From CategoryBases Where CategoryId = @CategoryId "; cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@CategoryId", id); //[1] SqlDataReader 형식의 개체로 결괏값 받기 SqlDataReader dr = cmd.ExecuteReader(); //[2] Read() 메서드로 데이터 있는만큼 반복 CategoryBase category = null; if (dr.Read()) { var categoryId = dr.GetInt32(0); var categoryName = (dr["CategoryName"] == DBNull.Value) ? "" : dr.GetString(1); // 개체 리터럴을 통해서 값 채우기 category = new CategoryBase { CategoryId = categoryId, CategoryName = categoryName }; } //[3] Close() 메서드로 연결된 리더 개체 종료 dr.Close(); con.Close(); return(category); }