2013-04-07 33 views
0

使用Visual Studio 2010時出現問題。我正在使用基於服務的數據庫(.mdf)。 我已經在Visual Studio中手動創建了一些包含一些信息的表格。我寫的代碼可以從表中讀取,但是當我插入新信息時,它看起來像是將數據添加到其他數據庫。C#數據庫寫入表不起作用

我可以從正確的表中讀取信息,但是當我向表中添加信息時,無法在Visual Studio中看到服務器資源管理器中的更改。

我不知道爲什麼要使用不同的數據庫!有人知道這個問題嗎?

這裏是我的代碼:

public class DataAccess 
{ 
    private SqlConnection sqlConnection; 
    private SqlCommand sqlCommand; 
    private SqlDataAdapter dataAdapterAnimal; 
    private DataSet dataset; 
    private string connectionString = DBAccessLayer.Properties.Settings.Default.AnimalDBConnectionString; 

    public DataSet LoadAnimalDataSet() 
    { 
     dataset = new DataSet(); 

     using (sqlConnection = new SqlConnection(connectionString)) 
     { 
      sqlConnection.Open(); 
      dataAdapterAnimal = new SqlDataAdapter("SELECT * FROM AnimalTable", sqlConnection); 
      dataAdapterAnimal.Fill(dataset, "AnimalTable"); 
      sqlConnection.Close(); 
      return dataset; 
     } 
    } 

    public void AddAnimal(int animalID, string name, double age, string category, string gender, string extraAnimalInfo) 
    { 

     sqlConnection = new SqlConnection(connectionString); 
     sqlCommand = new SqlCommand("INSERT INTO AnimalTable VALUES(@AnimalID, @Name, @Age, @Category, @Gender, @ExtraAnimalInfo)", sqlConnection); 

     try 
     { 
      sqlConnection.Open(); 
      sqlCommand.Parameters.Add(new SqlParameter("@AnimalID", animalID)); 
      sqlCommand.Parameters.Add(new SqlParameter("@Name", name)); 
      sqlCommand.Parameters.Add(new SqlParameter("@Age", age)); 
      sqlCommand.Parameters.Add(new SqlParameter("@Category", category)); 
      sqlCommand.Parameters.Add(new SqlParameter("@Gender", gender)); 
      sqlCommand.Parameters.Add(new SqlParameter("@ExtraAnimalInfo", extraAnimalInfo)); 
      sqlCommand.ExecuteNonQuery(); 
      sqlConnection.Close(); 
     } 
     catch (Exception ex) 
     { 
      throw; 
     } 
    } 
+0

請告訴我們你嘗試過的一些代碼。 – Bit 2013-04-07 14:47:45

+1

有什麼異常嗎?你確定該表中沒有觸發器嗎? – 2013-04-07 14:51:33

+1

很可能,您正在閱讀2個不同的數據庫。 VS會在您的項目/解決方案中爲您製作一份.mdf的副本。是這樣嗎? – IAbstract 2013-04-07 14:52:53

回答

3

我還沒有看到你的連接字符串 - 但是從你的描述,現在看來,這可能是這個問題就在這裏:

整個User InstanceAttachDbFileName=方法有缺陷 - 充其量!在Visual Studio中運行應用程序時,它將複製.mdf文件(從您的App_Data目錄到輸出目錄 - 通常爲.\bin\debug) - 最有可能爲,您的INSERT工作得很好 - 但是您只是看着錯誤.mdf文件到底!

如果你想堅持這種方法,那麼試着在myConnection.Close()調用上放一個斷點 - 然後用SQL Server Mgmt Studio Express檢查.mdf文件 - 我幾乎可以確定你的數據在那裏。

在我看來真正的解決方案

  1. 安裝SQL Server Express(和你已經做到這一點無論如何)

  2. 安裝SQL Server Management Studio中快速

  3. 創建您的數據庫SSMS Express,給它一個邏輯名稱(例如MyDatabase

  4. 使用其邏輯數據庫名稱連接到它(在服務器上創建時給出) - 並且不要亂用物理數據庫文件和用戶實例。在這種情況下,您的連接字符串將是這樣的:

    Data Source=.\\SQLEXPRESS;Database=MyDatabase;Integrated Security=True 
    

    和其他一切是正是和以前一樣......