我有一个 Windows 应用程序,它调用服务然后写入数据库。在写结果之前,我删除了旧数据。
Windows 应用程序使用每 5 分钟运行一次的计时器调用该服务。
问题是:即使我使用删除,代码也不会删除记录。如果我不使用计时器调用它,它就可以工作。
我使用事务,使用 EF 不起作用。它仍然不删除记录。
static void Main(string[] args)
{
//////Start Timer
Timer timer = new Timer();
timer.Interval = 5 * 60 * 1000; // converts ms to minutes
timer.Elapsed += new ElapsedEventHandler(InsertRecords);
timer.Enabled = true;
timerFired.WaitOne();
}
public void InsertRecords()
{
using (SqlConnection connection = new SqlConnection(connectionstr))
{
connection.Open();
// Delete old entries
SqlTransaction trans = connection.BeginTransaction();
string sql = "Delete from PhilaMethod ";
SqlCommand cmd = new SqlCommand(sql, connection, trans);
trans.Commit();
connection.Close();
}
var conn = connectionstr;
string SQL1 = "";
foreach (PhilaMethod phila in phila2)
{
SQL1 += "INSERT INTO PhilaMethod(Name,PS1,PS2,RSI1,) values ('" + phila.Name + "','"+phila.PS1+"','"+phila.PS2+"','"+phila.RSI1+"','"+phila.RSI2+"'); ";
}
string SQL2 = "Delete from philamethod";
using (SqlConnection connection = new SqlConnection(conn))
{
connection.Open();
SqlTransaction sqlTran = connection.BeginTransaction();
SqlCommand command = connection.CreateCommand();
command.Transaction = sqlTran;
try
{
command.CommandText = SQL2;
int rowsAffected = command.ExecuteNonQuery();
if(rowsAffected >= 0)
{
command.CommandText = SQL2;
int rowsAffected2 = command.ExecuteNonQuery();
if(rowsAffected2 == 0)
{
command.CommandText = SQL1;
rowsAffected += command.ExecuteNonQuery();
}
}
慕容708150
元芳怎么了
相关分类