2014-04-26 57 views
0

當我單擊更新按鈕時,它顯示成功,但我的數據庫未更新。 什麼是錯我的代碼:爲什麼我的更新查詢不起作用

private void CmdUpdate_Click(object sender, EventArgs e) 
{ 
    SqlConnection conn = new SqlConnection(@"Data Source......"); 
    conn.Open(); 
    SqlCommand comm = new SqlCommand("update Leaves_Type set Leaves='"+txtltype.Text+"' where Leaves='"+txtltype.Text+"'");   
    comm.Connection = conn; 
    comm.ExecuteNonQuery(); 
    MessageBox.Show("Successfully Updated"); 
    conn.Close(); 
} 
+0

你試過運行此確切的查詢,看看它是否工作不使用c#? –

+4

事實上,你沒有使用查詢參數,並且在表單方法中有數據庫邏輯,它直接讀取控件,這使我不得不脫髮。 – Euphoric

+0

@Euphoric。 SqlCommand通訊=新的SqlCommand(「更新Leaves_Type設置葉= @葉」); comm.Parameters.AddWithValue(「@ Leaves」,txtltype.Text);但它顯示PRIMARY KEY約束'PK_Leaves_Type'的錯誤違規。無法在對象'dbo.Leaves_Type'中插入重複鍵。 該聲明已被終止。 – user3488317

回答

1
update Leaves_Type set Leaves='"+txtltype.Text+"' where Leaves='"+txtltype.Text+"'" 

你想要看什麼更新?您用相同的值更新字段。

+0

我調試了我的代碼。它顯示txtltype =我更新的值。是的,我想更新相同的價值 – user3488317

+1

更新相同的價值是什麼意思?假設'Leaves ='A'',並將其設置爲'A'。什麼意思? –

+0

在窗體中看到一個文本框和一個命令按鈕。在這裏我添加Leave_Type(EL/CL)。假設我錯誤地添加了ELE而不是El.now我想編輯這個。我怎樣才能做到這一點 。 – user3488317

0

我認爲在你的情況下,關於錯誤,你違反了PRIMARY KEY constraint。您可以嘗試使用Primary Key進行更新。並且使用參數化的SQL。

取而代之的是:

update Leaves_Type set Leaves='"+txtltype.Text+"' where Leaves='"+txtltype.Text+"'" 

你可以這樣做:

update Leaves_Type set Leaves='"+txtltype.Text+"' where LeavesID= someValue " //And you can retrieve 
       // someValue by appropriate Request if LeavesID is your PrimaryKey 
+0

我有多一個文本框for leaveid。 – user3488317

+0

閱讀我的評論後。因爲您正嘗試通過相同的值更新值。 –