2013-11-21 44 views
1

這裏是我的代碼無法保存數據的C#Windows應用程序

private void button1_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      string connectionString = @"Data Source=|DataDirectory|\Database_POS.sdf"; 
      using (SqlConnection connection = new SqlConnection(connectionString)) 
      using (SqlCommand command = connection.CreateCommand()) 
      { 
       command.CommandText= "INSERT INTO Customer (Email) Values (@email);"; 
       command.Parameters.AddWithValue("@email",textBox_Email.Text); 

       connection.Open(); 
       command.ExecuteNonQuery(); 
      } 
     } 

     catch (SqlException ex) 
     { 
      Console.WriteLine(ex.Message); 
     } 
    } 

這裏是我的設計

enter image description here

I am only trying to save 'email' here. 

這裏是我的SQL表,問題是,我甚至不能保存單場成表。

enter image description here

數據庫設計現在 enter image description here

錯誤是這樣

enter image description here

+2

你這裏得到什麼錯誤.. – Anand

+0

是'connectionString'正確的,你跟蹤利用破發點? – zey

+0

當你將它傳遞給command.parameters.addwithvalue()時,你會獲得textbox_Email.text的值嗎?你是如何得到其他值到數據庫 – ReubenTellis

回答

1

感謝大家的答案

Cannot connect to local database in C#

我得到了上面的鏈接我的回答形式。

我正在使用壓縮數據庫並試圖連接像SQLServer。

現在得到它的工作。

這裏就是答案文本,即解決了我的問題

When using a .sdf file (SQL Server Compact Edition), you need to use SqlCeConnection and not SqlConnection (that works against a full SQL Server): 
+1

哦!我錯過了那個!問題解決了。 –

1

有些事情要檢查:

  1. 待辦事項你的事件發生錯誤?如果是,那麼錯誤是什麼?請注意,您正在將錯誤消息寫入控制檯窗口,但您的應用程序是Windows應用程序。您的應用程序是否有控制檯窗口?如果否,請在Visual Studio中檢查輸出窗口。或者更簡單,使用MessageBox.Show來顯示錯誤。

  2. 如果程序運行時沒有任何錯誤,請檢查返回值command.ExecuteNonQuery()。它會告訴你有多少記錄受到影響。如果它多於零,則該值確實存儲在數據庫中。

  3. 確保您看到了要插入到程序中的數據庫文件的內容!您可能從項目目錄中打開了Database_POS.sdf,但該程序會將數據插入「bin \ Debug」目錄中的另一個Database_POS.sdf

- 更多幫助 -

你的方法更改爲:

private void button1_Click(object sender, EventArgs e) 
{ 
    try 
    { 
     string connectionString = @"Data Source=|DataDirectory|\Database_POS.sdf"; 
     using (SqlConnection connection = new SqlConnection(connectionString)) 
     using (SqlCommand command = connection.CreateCommand()) 
     { 
      command.CommandText= "INSERT INTO Customer (Email) Values (@email);"; 
      command.Parameters.AddWithValue("@email",textBox_Email.Text); 

      connection.Open(); 
      var rowsAffected = command.ExecuteNonQuery(); 
      if(rowsAffected > 0) 
       MessageBox.Show("Data inserted successfully"); 
      else 
       MessageBox.Show("Nothing inserted into the database!"); 
     } 
    } 

    catch (SqlException ex) 
    { 
     Console.WriteLine(ex.Message); 
     MessageBox.Show(ex.ToString()); // for debugging purpose 
    } 
} 
+0

謝謝,我正在收集圖片請問test and reply asap –

+0

更新了我的問題 –

相關問題