ExecuteNonQuery requires the command to have a transaction error in my code

旧城冷巷雨未停 提交于 2019-11-28 20:03:53
Steve

You need to change this line

SqlCommand cmd = new SqlCommand("update Contact_Info set CustInfo=" + ds.GetXml() + 
                                " WHERE Customer_ID=" + a + "", scon);

in this way

SqlCommand cmd = new SqlCommand("update Contact_Info set CustInfo=" + ds.GetXml() + 
                  " WHERE Customer_ID=" + a + "", scon, sqlTrans);

The error message states exactly the problem. Before code reaches that line you have opened a transaction and it is still open at the point of error

.....
scon.Open();       
SqlTransaction sqlTrans = scon.BeginTransaction();
.....       

Now, every SqlCommand executed when the connection has an opened transaction need to be informed of this. The transaction is not automatically set by the Framework.
You can use the SqlCommand constructor, as explained above, or you can set the cmd.Transaction property before executing the command.

Note: Avoid at all cost the use of string concatenation when using query text to update/insert/delete/select on a database. Use parameters. This will avoid problems with strange or invalid characters and most important will prevent SqlInjection Attacks

string sqlText = "update Contact_Info set CustInfo=@info WHERE Customer_ID=@id";
SqlCommand cmd = new SqlCommand(sqlText, scon, sqlTrans);  
cmd.Parameters.AddWithValue("@info", ds.GetXml());
cmd.Parameters.AddWithValue("@id",a);
cmd.ExecuteNonQuery();  

You have started a transaction that is not commited before you called cmd.ExecuteNonQuery().

Just write down cmd.Transaction = sqlTrans; just before cmd.ExecuteNonQuery();

it will ensure that Now ExecuteNonQuery() will be executed in same transaction and also will be able to see all the modification done to database in the same transaction.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!