任何人都可以帮我修改下面的代码。我试图捕获数据库表而不是文件中的错误。
当前代码正在将错误写入日志表,我们如何修改以将相同的错误写入表。
码
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.AppendText(Dts.Variables["User::LogFolder"].Value.ToString()
+ "\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
如果可能,请分享您的宝贵建议。
...谢谢
答案 0 :(得分:1)
首先,我会在尝试之前将sql对象创建移动到,否则你需要在catch块中重复它,它取决于你。
ConnectionManager ConMgr = Dts.Connections.Add("ADO.NET:SQL");
ConMgr.ConnectionString = "data source=database;initial catalog=zzzz_PRC;integrated security=true;persist security info=True;";
ConMgr.Name = "DBConn";
ConMgr.Description = "DBConn";
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)
(Dts.Connections["DBConn"].AcquireConnection(Dts.Transaction) as SqlConnection);
接下来只运行查询而不是记录到文件:
catch (Exception exception)
{
string query = "Insert into " + SchemaName + ".logtable (Logtextcolumn) "; -- change tablename and columns desired.
query += "VALUES('" + exception.ToString() + "')";
SqlCommand myCommand1 = new SqlCommand(query, myADONETConnection);
myCommand1.ExecuteNonQuery();
Dts.TaskResult = (int)ScriptResults.Failure;
}
}