简体   繁体   English

C#中的SQL更新语句的日期问题

[英]Date Issue with SQL update statement in c#

I have a Date field in a table that is displayed as Day-Month-Year Hour.Minute.Seconds and I am trying to update the HOUR field when there is the same Ertnumber and Date. 我在显示为“日-月-年Hour.Minute.Seconds”的表中有一个“日期”字段,并且当Ertnumber和Date相同时,我试图更新HOUR字段。 I can get the field to update with the same Ertnumber but when I try to make sure the date is the same I get an error. 我可以使用相同的Ertnumber来更新该字段,但是当我尝试确保日期相同时,会出现错误。 I am having troubles making my DateTime format the same as sqls. 我在使DateTime格式与sqls相同时遇到麻烦。 I create the DateTime in c# by: 我通过以下方式在c#中创建DateTime:

DateTime dateStamp = new DateTime(2013, 2, 14, 1, 0, 0);

Here is my update string. 这是我的更新字符串。

String.Format("update sdeadmin.meter_data_fixed_network set HOUR{2} = {0} where ERTNUMBER = '{1}' and DATETIME = '{3}'", this.Read, this.ertNumber, this.Stamp.Hour, this.DateStamp.ToString("MMddyyyyHHmmss"));

尝试执行以下操作: SQL查询的Datetime参数您应该执行参数化查询,而不是String.Format()

Parameterization of your query should resolve this issue; 查询的参数化应该可以解决此问题; however, your problem is actually in two parts; 但是,您的问题实际上分为两部分; you need to first build the query which references a column name that can change, HOUR+stamp.Hour, and the query parameters. 您需要首先构建查询,该查询引用可以更改的列名称, HOUR+stamp.Hour,和查询参数。

Therefore, something like the following should work for you: 因此,类似以下的内容应该适合您:

string query = 
   String.Format("update sdeadmin.meter_data_fixed_network SET HOUR{0} = @read WHERE ERTNUMBER = @ertnumber AND DATETIME = @date;", this.Stamp.Hour);

This builds your basic query - you know have a parameterized query that will update the respective HOUR column of sdeadmin.meter_data_fixed_network . 这将构建您的基本查询-您知道有一个参数化查询,该查询将更新sdeadmin.meter_data_fixed_network的相应HOUR列。 All that remains is create a connection object, a command object, and add the parameters to it before executing it. 剩下的就是创建一个连接对象,一个命令对象,并在执行之前向其添加参数。

For example: 例如:

//Create the connection
using(SqlDbConnection connection = new SqlDbConnection("your_connection_string"))
{
    //Create the Command
    using(SqlDbCommand command = new SqlDbCommand(query))
    {
      //Set up the properties of the command and the parameters
      command.CommandType = CommandType.Text;
      command.Connection = connection;
      command.Parameters.AddWithValue("@read", Read);
      command.Parameters.AddWithValue("@ertnumber", ertNumber);
      command.Parameters.AddWithValue("@date", DateStamp);
      //Have to open the connection before we do anything with it
      connection.Open();
      //Execute the command. As we don't need any results back we use ExecuteNonQuery   
      command.ExecuteNonQuery();

    }
}//At this point, connection will be closed and disposed - you've cleaned up

There are several advantages to parameterizing your query: 参数化查询有几个优点:

  1. You can help prevent sql injection attacks 您可以帮助防止sql注入攻击
  2. Many database engines can reuse execution plans for parameterized queries, improving performance 许多数据库引擎可以将执行计划重用于参数化查询,从而提高性能

@JeffAtwood wrote on this subject a few years ago: http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html @JeffAtwood几年前就写过这个主题: http : //www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html

Also note the use of the USING statement. 还要注意USING语句的使用 This will ensure that the connection and command objects are disposed as soon as you leave the scope of the respective usings. 这将确保在您离开相应用途的范围后立即处置连接和命令对象。 This is important as, although .Net will manage the resources it has control over, it cannot manage external resources like file handles, database connections etc, so it's important you clean up after yourself. 这很重要,因为尽管.Net将管理它可以控制的资源,但它无法管理外部资源(例如文件句柄,数据库连接等),因此,请务必自己清理。 The Dispose for Connection will also explicitly close it. Dispose for Connection也将显式关闭它。

(Assuming you mean SQL Server): The best date format to use with SQL Server is ISO 8601: (假设您是指SQL Server):与SQL Server一起使用的最佳日期格式是ISO 8601:

yyyyMMdd HHmmss. yyyyMMdd HHmmss。

HOWEVER, writing your SQL with String.Format is a terrible practice. 但是,用String.Format编写SQL是一种糟糕的做法。 Use System.Data.SQLClient.SQLCommand with parameters and the format won't bother you. 将System.Data.SQLClient.SQLCommand与参数一起使用,格式不会打扰您。

DateTime dateStamp = new DateTime(2013, 2, 14, 1, 0, 0);

System.Data.SQLClient.SQLConnection cxn; // make sure to set this up and open it

System.Data.SQLClient.SQLCommand cmd = new System.Data.SQLClient.SQLCommand(
     String.Format("update sdeadmin.meter_data_fixed_network set HOUR{0} = @value where ERTNUMBER = @ert and DATETIME = @date", this.Stamp.Hour)
     ,cxn );

cmd.Parameters.Add(new SqlParameter("@value", this.Read);
cmd.Parameters.Add(new SqlParameter("@ert", this.ertNumber);
cmd.Parameters.Add(new SqlParameter("@date", this.Stamp);
cmd.ExecuteNonQuery();

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

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