public class InsertDBHandler:IHandler {
Log lg = null;
SqlConnection sqlconnection = null;
#region IHandler Members
SqlCommand cmd = new SqlCommand();
public InsertDBHandler()
{
lg = new Log();
}
public bool FrameReceived(IMessage response)
{
sqlconnection = new SqlConnection(SQLHelper.ConnectionStringLocalTransaction);
Message msg = (Message)response;
SqlTransaction tras = null;
int r1 = 0;
int r2 = 0;
int r3 = 0;
try {
if (sqlconnection.State !=ConnectionState.Open)
{
sqlconnection.Open();
}
tras = sqlconnection.BeginTransaction();
cmd.Connection = sqlconnection;
cmd.Transaction = tras;
foreach (Anchor anchor in msg.anchors)
{
foreach (Tag tag in anchor.tags)
{
cmd.CommandText = "insert into TagBlinkLogs (TagId,AnchorId,period,countdown,rxWindow,capabilities,SeqNo,BlinkState,PanicInfo,TimeStamp) values ('" + tag.tagid + "','" + anchor.AnchorId + "',3000,0,20,12,0,1,0,'" + tag.RecordTime + "')"; //
r1 = cmd.ExecuteNonQuery();
for (int i = 0; i < tag.Distince.Length; i++)
{
if (tag.Distince[i] != 0)
{
DateTime temp_time =tag.RecordTime.AddSeconds(20 * i);
cmd.CommandText = "insert into RangingReports (TagID,TimeStamp) values ('" + tag.tagid + "','" + temp_time + "')"; //
r2 = cmd.ExecuteNonQuery();
cmd.CommandText = "insert into DistanceReports (AnchorId,Distance,RangingReport_RangingReportId) values('" + anchor.AnchorId + "','" + tag.Distince[i] +"',@@identity)";
r3 = cmd.ExecuteNonQuery();
}
}
}
}
if (r1 > 0 && r2 > 0 && r3 > 0)
{
tras.Commit();
return true;
}
return false;
}
catch(SqlException ex)
{
lg.Write("数据库操作异常"+ex.Message);
tras.Rollback();
return false;
}
finally
{
sqlconnection.Close();
}
}
public bool FrameReceived(List<IMessage> messages)
{
bool result = false;
foreach(IMessage msg in messages)
{
result = FrameReceived(msg);
if (!result)
{
return false;
}
}
return result;
}
#endregion
}