我要求对表进行所有更改(例如插入,更新和删除)进行审计,并且我使用简单的SQLDataSource和GridView以及自动生成的INSERT / UPDATE / DELETE语句。问题是,当一行更新时我想获取ID(主键)并将其放入审计表中 - 但因为UPDATE查询的唯一参数是实际数据而不是主键,我不知道如何访问此信息。这是我的UPDATE查询:
InsertCommand="INSERT INTO [NominalCode] ([VAXCode], [Reference], [CostCentre], [Department], [ReportingCategory]) VALUES (@VAXCode, @Reference, @CostCentre, @Department, @ReportingCategory)"
以下是审计的代码隐藏:
protected void SqlDataSource1_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
string fields = e.Command.Parameters[0].Value.ToString() + "," + e.Command.Parameters[1].Value.ToString() + "," + e.Command.Parameters[2].Value.ToString() + "," + e.Command.Parameters[3].Value.ToString() + "," + e.Command.Parameters[4].Value.ToString();
System.Security.Principal. WindowsPrincipal p = System.Threading.Thread.CurrentPrincipal as System.Security.Principal.WindowsPrincipal;
string[] namearray = p.Identity.Name.Split('\\');
string name = namearray[1];
string queryString = "INSERT INTO Audit (source, action, item, userid, timestamp) VALUES (@source, @action, @item, @userid, @timestamp)";
using (SqlConnection connection = new SqlConnection("con string removed for privacy"))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("@source", "Nominal");
command.Parameters.AddWithValue("@action", "Update");
command.Parameters.AddWithValue("@item", fields);
command.Parameters.AddWithValue("@userid", name);
command.Parameters.AddWithValue("@timestamp", DateTime.Now);
connection.Open();
try
{
command.ExecuteNonQuery();
}
catch (Exception x)
{
Response.Write(x);
}
finally
{
connection.Close();
}
}
}
答案 0 :(得分:0)
好的,我觉得很蠢。当然,ID位于SQL查询的WHERE子句中!我出于某种原因粘贴在INSERT命令中。