2014-04-26 49 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

阅读我的评论后。因为您正尝试通过相同的值更新值。 –