2012-08-02 23 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並查看是否有錯誤。 – 2012-08-02 11:37:51

+0

我做過了,但沒有區別!? – 2012-08-02 11:39:27

+0

請發佈Guests表定義。 – 2012-08-02 11:47:14

回答

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

這不會只更新內存中的DataSet嗎?不是實際的數據庫表?我通常不使用SqlDataAdapter插入,只選擇,所以我真的不確定... – Mark 2012-08-02 12:11:51

+0

@Mark,我也沒有,所以我剛剛在本地進行了測試,並且此代碼也更新了數據庫。 – Andrei 2012-08-02 12:13:50

+0

甜!我將不得不考慮未來的發展!我唯一不喜歡的是將SQL編碼到應用程序中。我傾向於使用存儲過程。 – Mark 2012-08-02 12:24:58

相關問題