简体   繁体   English

从SQL表中删除行(日期和时间值错误)

[英]Delete row from SQL table (Date & Time values error)

I try to write and then delete from an SQL table. 我尝试编写然后从SQL表中删除。 My WRITE code is OK, however my DELETE code does not work as I want. 我的WRITE代码可以,但是我的DELETE代码无法正常工作。

//SQL_ConnectionString defined above
SqlConnection SQL_Connection = new SqlConnection(SQL_ConnectionString)

string   INSERT =  "INSERT INTO " + tbTable_DAQ.Text + " (Date, Time, Comment)";
string   VALUES =  "VALUES " + " (@Date,    @Time,   @Comment)";
string   SQL_WriteString =  INSERT + VALUES;

DateTime DateTimeNow = DateTime.Now;

try
{
   //get time
   DateTimeNow = DateTime.Now;

   //create SQL command object
   SqlCommand SQL_Write = new SqlCommand(SQL_WriteString, SQL_Connection);

   //attach values
   SQL_Write.Parameters.AddWithValue("@Date", DateTimeNow);
   SQL_Write.Parameters.AddWithValue("@Time", DateTimeNow);
   SQL_Write.Parameters.AddWithValue("@Comment", "Table Access Test. ");

   SQL_Write.ExecuteNonQuery();

   //dispose & nullify SQL_Write
   SQL_Write.Dispose();
   SQL_Write = null;
}

catch (Exception eWrite) 
{ 
   MessageBox.Show(eWrite.ToString(), "SQL WRITE ERROR", MessageBoxButtons.OK, 
                                       MessageBoxIcon.Exclamation); 
}

//now delete inserted row from SQL table            
string DELETE = "DELETE FROM " + tbTable_DAQ.Text + " ";
string FROM =  "WHERE " + "Date = " + DateTimeNow  + "AND " + "Time = " + DateTimeNow 
               + "AND " + "Comment='Table Access Test.'"; //not working
string   SQL_DeleteString  = DELETE + FROM;

try 
{ 
   //create SQL command object
   SqlCommand SQL_Delete = new SqlCommand(SQL_DeleteString, SQL_Connection);
   SQL_Delete.ExecuteNonQuery();
   //dispose & nullify SQL_Delete
   SQL_Delete.Dispose();
   SQL_Delete = null;
}

catch (Exception eDelete)     
{ 
     MessageBox.Show(eDelete.ToString(), "SQL DELETE ERROR", MessageBoxButtons.OK, 
                       MessageBoxIcon.Exclamation); 
}

It give me an error. 它给我一个错误。 I believe the error is due to the values of the Date and Time column. 我认为该错误是由于“日期和时间”列的值引起的。 On the WRITE code, I think the SQL table converts DateTimeNow to on receiving it on the Date (date type) and Time (time7 type). 在WRITE代码上,我认为SQL表在Date (日期类型)和Time (time7类型)上接收到它后,会将DateTimeNow转换为。 However, to delete that specific row the values must match (no conversion is done) and I do not know how to get the values right. 但是,要删除该特定行,值必须匹配(不进行任何转换),而且我不知道如何正确获取值。

You are checking against datetime values that are very specific. 您正在检查非常具体的日期时间值。 Unless you have tables records that are EXACTLY the same date and time, this will never work. 除非您有完全相同的日期和时间的表记录,否则它将永远无法工作。

Also, you are checking both what I assume is a date field and a time field against a datetime. 另外,您正在检查我假设是日期字段和时间字段是否与日期时间相对。 Why aren't you just comparing one datetime field? 您为什么不只比较一个日期时间字段?

Your insert works becuase you're using SQL parameters to pass values to SQL which is great. 您的插入有效,因为您正在使用SQL参数将值传递给SQL,这很棒。 Your DELETE probably fails on a Syntax error (it would be nice if you included the text of the error) because you're building a string and trying to execute it. 您的DELETE可能由于语法错误而失败(如果您包含错误的文本,那会很好),因为您正在构建字符串并尝试执行它。

You can probably fix the delete-string by putting single-quotes around your dates but I don't even want to show you the right syntax. 您可能可以通过在日期前后加上单引号来修复删除字符串,但我什至不想显示正确的语法。 I'd rather you use SQL parameters again for two BIG reasons: 我宁愿您再次出于两个大原因使用SQL参数:

  1. SQL will do the right conversion for you - no worries about getting the text right. SQL将为您完成正确的转换-无需担心正确的文本。
  2. You're protecting yourself from SQL injection - a MAJOR security problem caused by building SQL strings and executing them. 您正在保护自己免受SQL注入的侵害-这是由构建SQL字符串并执行它们引起的主要安全问题。

Please try sending the DateTime.Now formatted to Sql proc as string 请尝试将DateTime.Now格式化为字符串发送给Sql proc

eg like this 例如这样

string formatted = dateNow.ToString("yyyyMMdd");

If your autocommit isnt on you should type connection.transaction.commit. 如果您没有启用自动提交功能,则应输入connection.transaction.commit。 I think it would be better if you catch a status and finally test like this: 我认为如果您能获得一个状态并最终像这样进行测试会更好:

finally
{
  if (status)
  {
    connection.transaction.commit;
  }
  else
  {
    connection.transaction.rollback;
  }
}

Maybe your code try to delete a row which isnt inserted because of no commit. 也许您的代码尝试删除由于未提交而未插入的行。 But normaly it should be the datetime problem ;-) 但是通常这应该是日期时间问题;-)

Alright, So base on n8wrl's suggestion, I do not use the strings for my SQL DELETE code. 好的,因此基于n8wrl的建议,我不将字符串用于SQL DELETE代码。 I changed it to: 我将其更改为:

        //now delete inserted row from SQL table            
        string DELETE = "DELETE FROM " + tbTable_DAQ.Text + " ";
        string FROM = "WHERE " + "Date = @Date" + " AND " + "Time = @Time" + " AND " + "Comment = @Comment";
        string SQL_DeleteString = DELETE + FROM;

        try
        {
           //create SQL command object
           SqlCommand SQL_Delete = new SqlCommand(SQL_DeleteString, SQL_Connection);

           //attach values
           SQL_Delete.Parameters.AddWithValue("@Date",               DateTimeNow.Date);
           SQL_Delete.Parameters.AddWithValue("@Time",               DateTimeNow.TimeOfDay);
           SQL_Delete.Parameters.AddWithValue("@Comment",            "Table Access Test.");

           SQL_Delete.ExecuteNonQuery();

           //dispose & nullify SQL_Delete
           SQL_Delete.Dispose();
           SQL_Delete = null;
        }

        catch (Exception eDelete) { MessageBox.Show(eDelete.ToString(), "SQL DELETE ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); }

and things work fine. 一切正常。 Thanks to Hatsoft for your help. 感谢Hatsoft的帮助。 I think it is best to avoid the messy string method. 我认为最好避免使用凌乱的字符串方法。 I do not want any injection attack. 我不要任何注射攻击。 I will be any MAJOR problem if that happens. 如果发生这种情况,我将是任何重大问题。 I mean, REALLY MAJOR. 我的意思是,非常重要。

There are two different DateTimeNow variables that likely contain two slightly different values which would make an "exact match" fail. 两个不同的 DateTimeNow变量,它们可能包含两个稍有不同的值 ,这会使“完全匹配”失败。

Remove the nested one in the try/catch of the UPDATE that shadows the outer variable; 删除隐藏外部变量的UPDATE的try/catch中的嵌套嵌套; I suspect it might "work" then. 我怀疑那可能“起作用”。

However, it generally is an error to look for such an "exact" time. 但是,寻找这样的“准确”时间通常是错误的。 Perhaps you mean to look for "with the same minute" or similar? 也许您的意思是寻找“同一分钟”或类似的内容?

Also, where are both the DATE and TIME columns being fed a DateTime? 另外,DATE和TIME列都在哪里输入DateTime? And what DB types do they represent? 它们代表什么数据库类型?

And please fix the DELETE to use parameters like the UPDATE does .. there is no point regressing to not using parameters when the .NET framework handles them rather well. 并且请修复 DELETE以使用UPDATE之类的参数..当.NET框架很好地处理它们时,毫无意义地回归为不使用参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM