2015-07-10 25 views
0

我試圖使用SQL參數將我的文本框中的文本添加到SQL數據庫中。試圖將文本從文本框添加到SQL表中的C#

我已經測試了連接,它打開好,但我仍然從try,catch語句中得到異常。任何想法,我可能會出錯?

這裏是我的代碼:

private void button3_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      SqlConnection cnn = new SqlConnection(@"Server=.\SQLEXPRESS;Initial Catalog=MyAdventureWorks;Trusted_Connection=yes;"); 


      SqlCommand addEmployee = new SqlCommand("INSERT INTO dbo.DimEmployee (ParentEmployeeKey, FirstName, LastName, NameStyle, CurrentFlag, SalesPersonFlag)" + "Values (@parentEmployeeKey,@firstName, @lastName, @nameStyle, @currentFlag, @salesPersonFlag)", cnn); 

      addEmployee.Parameters.AddWithValue("@parentEmployeeKey", textBox1.Text); 
      addEmployee.Parameters.AddWithValue("@firstName", textBox2.Text); 
      addEmployee.Parameters.AddWithValue("@lastName", textBox3.Text); 
      addEmployee.Parameters.AddWithValue("@nameStyle", textBox4.Text); 
      addEmployee.Parameters.AddWithValue("@currentFlag", textBox5.Text); 
      addEmployee.Parameters.AddWithValue("@salesFlag", textBox6.Text); 

      cnn.Open(); 
      addEmployee.ExecuteNonQuery(); 
      cnn.Close(); 

      MessageBox.Show("Employee added to database"); 
     } 
     catch (SqlException ex) 
     { 
      MessageBox.Show("An unknown error occured"); 
     } 
+0

什麼是異常_exactly_? –

+0

可以修改[MessageBox.Show(「未知錯誤發生」);]行以顯示存儲在ex變量中的實際錯誤。然後你就會知道到底出了什麼問題! –

回答

1

如果是這樣的話,你定義你的最後一個參數在你的命令@salesPersonFlag但您嘗試參數採集與@salesFlag名稱添加此值。他們應該是一樣的。

更改

addEmployee.Parameters.AddWithValue("@salesFlag", textBox6.Text); 

addEmployee.Parameters.AddWithValue("@salesPersonFlag", textBox6.Text); 

還可以使用using statement處置您的連接和命令自動代替手動調用Close()方法。

並且儘可能不要使用AddWithValueIt may generate unexpected and surprising results sometimes。使用Add方法重載指定您的參數類型及其大小。

using(var cnn = new SqlConnection(conString)) 
using(var addEmployee = con.CreateCommand()) 
{ 
    // Set your CommandText property 
    // Add your parameter values with Add method3 
    // Open your connection 
    // Execute your query 
} 
+0

嗨。我的錯誤是錯誤輸入了變量;但是,它不適用。 –

+0

你能告訴我如何通過'使用'也使用連接? –

+0

@NickProud我_did_在我的例子中。你能否詳細說明_does不能正常工作?你得到了什麼異常或錯誤信息?沒有這些信息,它不可能幫助你。 –

相關問題