2012-08-02 3 views
1

아래의 코드에서 이름, 나이, 성별 및 정보와 같은 모든 데이터를 각 객체에서 저장하기 위해 목록에 대한 참조와 함께 메서드를 호출하지만 응용 프로그램을 테스트 한 후에는 테이블이 비어 있습니다! 내가 뭔가를 놓쳤거나 잘못 했습니까? 나는 아무런 오류가 없다.테이블에 데이터를 저장하지 못합니까?

public void SaveDataToDB(List<Animal> animals) 
    { 
     connection = new SqlConnection(connectionString); 
     dataset = new DataSet(); 
     sql = "SELECT * From Guests"; 

     try 
     { 
      connection.Open(); 
      adapter = new SqlDataAdapter(sql, connection); 
      adapter.Fill(dataset, "Guests"); 

      foreach (Animal animal in animals) 
      { 
       DataRow row = dataset.Tables["Guests"].NewRow(); 
       row["Name"] = animal.Name; 
       row["Age"] = animal.Age; 
       row["Gender"] = animal.Gender; 
       row["Info"] = animal.ImportantInfo; 

       dataset.Tables["Guests"].Rows.Add(row); 
      } 
      new SqlCommandBuilder(adapter); 
      adapter.Update(dataset.Tables["Guests"]); 
      connection.Close(); 
     } 
     catch 
     { 
      throw; 
     } 
    } 
+0

catch 절에 오류를 다시 게시하기 때문에 오류가 발생하지 않을 수도 있습니다. try..catch를 제거하고 오류인지 확인하십시오. –

+0

하지만 차이는 없었습니다!? –

+0

손님 테이블 정의를 게시하십시오. –

답변

1

삽입물이 올바르게 작동하려면 어댑터에 InsertCommand을 정의해야합니다. 다음은 샘플입니다.

public void SaveDataToDB(List<Animal> animals) 
{ 
    SqlConnection connection = new SqlConnection(connectionString); 
    DataSet dataset = new DataSet(); 
    string sql = "SELECT * From Guests"; 

    try 
    { 
     connection.Open(); 
     SqlDataAdapter adapter = new SqlDataAdapter(sql, connection); 
     adapter.Fill(dataset, "Guests"); 

     // Create the InsertCommand. 
     SqlCommand command = new SqlCommand(
      "INSERT INTO Guests (Name, Age, Gender, ImportantInfo) " + 
      "VALUES (@Name, @Age, @Gender, @ImportantInfo)", connection); 

     // Add the parameters for the InsertCommand. 
     command.Parameters.Add("@Name", SqlDbType.NVarChar, 50, "Name"); 
     command.Parameters.Add("@Age", SqlDbType.Int, 4, "Age"); 
     command.Parameters.Add("@Gender", SqlDbType.NVarChar, 6, "Gender"); 
     command.Parameters.Add("@ImportantInfo", SqlDbType.NVarChar, 100, "ImportantInfo"); 

     foreach (Animal animal in animals) 
     { 
      DataRow row = dataset.Tables["Guests"].NewRow(); 
      row["Name"] = animal.Name; 
      row["Age"] = animal.Age; 
      row["Gender"] = animal.Gender; 
      row["Info"] = animal.ImportantInfo; 

      dataset.Tables["Guests"].Rows.Add(row); 
     } 
     new SqlCommandBuilder(adapter); 
     adapter.Update(dataset.Tables["Guests"]); 
     connection.Close(); 
    } 
    catch 
    { 
     throw; 
    } 
} 

db 매개 변수의 실제 db 유형 및 크기를 지정하십시오.

+0

메모리 내 데이터 집합 만 업데이트하지 않습니까? 실제 데이터베이스 테이블이 아닙니까? 저는 SqlDataAdapter를 인서트에만 사용합니다. Selects만으로는 정말 확신 할 수 없습니다 ... – Mark

+0

@Mark, 어느 쪽도하지 않으므로 로컬로 테스트 했으므로이 코드도 데이터베이스를 업데이트합니다. – Andrei

+0

달콤한! 나는 앞으로의 개발을 고려해야 할 것이다! 내가 좋아하지 않는 유일한 방법은 응용 프로그램에 SQL을 하드 코딩하는 것입니다. 나는 저장 프로 시저를 사용하는 경향이있다. – Mark

관련 문제