我試圖使用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");
}
什麼是異常_exactly_? –
可以修改[MessageBox.Show(「未知錯誤發生」);]行以顯示存儲在ex變量中的實際錯誤。然後你就會知道到底出了什麼問題! –