C#和SQL更新查询 [英] C# and SQL update query
问题描述
我有这段代码应该更新数据库中表中的一行.
如果我直接在SQL Server中将其作为查询编写,则该查询有效,但在C#上下文中则无效.有人可以给我解释一下我应该怎么做才能完成这项工作:
这是我的代码:
I have this code that should update a row in a table from a database.
The query works if I write it in SQL server directly as a query, but it doesn''t work from a C# context. Can somebody please explain me what I should do to make this work:
this is my code:
//Pas huidig saldo kassa aan:
public void huidigSaldoKassaAanpasser(int kassaID, double bedrag)
{
SqlTransaction transactie = null;
try
{
if (connectie.State == System.Data.ConnectionState.Closed)
{
connectie.Open();
}
transactie = connectie.BeginTransaction();
SqlCommand cmdHaalGegevensOp = new SqlCommand(@"Update Kassa SET huidigsaldo = @bedrag
WHERE id = @kassaID");
cmdHaalGegevensOp.Connection = connectie;
cmdHaalGegevensOp.Transaction = transactie;
cmdHaalGegevensOp.Parameters.AddWithValue("@kassaID", kassaID);
cmdHaalGegevensOp.Parameters.AddWithValue("@bedrag", bedrag);
cmdHaalGegevensOp.ExecuteNonQuery();
}
catch (Exception ex)
{
if (transactie != null)
{
transactie.Rollback();
}
throw ex;
}
finally
{
connectie.Close();
}
}
不幸的是,每次我运行这段代码时,我都没有异常,但是该行没有更新. int kassaID和double bedrag是正确的.
如果我在SQL Server Management Studio中将其作为新查询编写为:
更新Kassa SET huidigsaldo = 598 WHERE ID = 7;
一切正常.
Unfortianetly everytime i run this code, I get no exceptions but the row isn''t updated. The int kassaID and the double bedrag are correct.
If I write it as this in SQL server management studio as a new Query:
Update Kassa SET huidigsaldo = 598 WHERE id = 7;
everything works fine.
推荐答案
它永远不会更新,因为您没有提交事务-您只需关闭它即可.在ExecuteNoQuery调用之后,添加以下行:
It is never updated because you do not Commit the transaction - you just close it. After the ExecuteNoQuery call, add the line:
transactie.Commit();
能否告诉我数据库中"huidigsaldo"字段的类型,如果它是int,添加时必须将参数"bedrag"转换为in,请参见下面的代码
can you tell me the type of "huidigsaldo" field in the database, if it is an int, you have to convert parameter "bedrag" to in when you are adding , see code as below
cmdHaalGegevensOp.Parameters.AddWithValue("@bedrag",Convert.ToInt32(bedrag));
这篇关于C#和SQL更新查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!