[英]Catch exception and save to SQL Server
I'm catching an exception and I want to write this to SQL Server, but my program doesn't write... 我正在捕获异常,我想将其写入SQL Server,但我的程序不写...
I haven't received any error, but in SQL Server I haven't found anything... 我没有收到任何错误,但在SQL Server中我没有发现任何东西......
catch (Exception f)
{
String error = f.ToString();
SqlConnection konekt = new SqlConnection(connectionstring);
SqlCommand prikaz = new SqlCommand("insert into ERROR_LOG (ULOHA, OPERACE, POPIS, MESSAGE, DATUM) values ('3', '3', 'Chyba v ExportNOHEL', @error, @datum)", konekt);
konekt.Open();
prikaz.Parameters.AddWithValue("@error", error);
prikaz.Parameters.AddWithValue("@datum", DateTime.Now);
prikaz.ExecuteNonQuery();
konekt.Close();
}
Have you any idea where is the problem? 你知道问题在哪里吗?
If you aren't getting any errors, and you are 100% sure that you are indeed writing to the correct database, then it may be that you have an ambient transaction, such as TransactionScope
(which is rolling back your transaction) 如果您没有收到任何错误,并且您100%确定您确实正在写入正确的数据库,则可能是您有环境事务,例如
TransactionScope
(正在回滚您的事务)
A way to check this is to place a breakpoint on konekt.Close();
检查这个的方法是在
konekt.Close();
上放置一个断点konekt.Close();
and then switch to SQL Query Analyzer and do 然后切换到SQL查询分析器并执行
select * from error_log (NOLOCK)
to see if the log is there. 查看日志是否存在。 If it is, and then getting rolled back when you continue your code, you can suppress the ambient transaction as follows:
如果是,然后在继续代码时回滚,则可以按如下方式禁止环境事务:
using (new TransactionScope(TransactionScopeOption.Suppress))
using (var konekt = new SqlConnection(connectionstring))
using (var prikaz = new SqlCommand("insert into ERROR_LOG (ULOHA, OPERACE, POPIS, MESSAGE, DATUM) values ('3', '3', 'Chyba v ExportNOHEL', @error, @datum)", konekt))
{
konekt.Open();
prikaz.Parameters.AddWithValue("@error", "ASASAS");
prikaz.Parameters.AddWithValue("@datum", DateTime.Now);
prikaz.ExecuteNonQuery();
konekt.Close();
}
Depending on the datatype which you have it maybe that the data is getting truncated if error
is too large. 根据您拥有的数据类型,如果
error
太大,数据可能会被截断。 This might help: 这可能有所帮助:
String or binary data would be truncated SQL Error 字符串或二进制数据将被截断SQL错误
虽然你所做的事情看起来没有任何错误,但是将SQL语句硬编码到c#中会使调试变得困难,我建议在数据库中为此创建一个新的存储过程,然后你可以更好地监控动作,通过在存储过程中创建一个正确的try catch,您可以更好地发现出错的地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.