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

时间:2013-05-15 16:57:12

标签: c# sql date sql-update

我在表格中有一个Date字段,显示为Day-Month-Year Hour.Minute.Seconds,我正在尝试在有相同的Ertnumber和Date时更新HOUR字段。我可以使用相同的Ertnumber来更新字段,但是当我尝试确保日期相同时,我收到错误。我遇到麻烦使我的DateTime格式与sqls相同。 我在c#中创建了DateTime:

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

这是我的更新字符串。

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"));

3 个答案:

答案 0 :(得分:4)

尝试做这样的事情: Datetime parameter for SQL Queries 您应该进行参数化查询,而不是String.Format()

答案 1 :(得分:2)

查询的参数化应解决此问题;但是,你的问题实际上分为两部分;您需要首先构建引用可以更改的列名称HOUR+stamp.Hour,和查询参数的查询。

因此,以下内容适用于您:

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

这会构建您的基本查询 - 您知道有一个参数化查询,它将更新HOUR的相应sdeadmin.meter_data_fixed_network列。剩下的就是创建一个连接对象,一个命令对象,并在执行它之前向它添加参数。

例如:

//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

参数化查询有几个好处:

  1. 您可以帮助防止SQL注入攻击
  2. 许多数据库引擎可以重用参数化查询的执行计划,从而提高性能
  3. 几年前@JeffAtwood写了这个主题:http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html

    还要注意使用USING语句。这将确保在您离开相应使用范围后立即处置连接和命令对象。这很重要,因为虽然.Net将管理它控制的资源,但它无法管理外部资源,如文件句柄,数据库连接等,因此您自己清理后很重要。 Dispose for Connection也将明确关闭它。

答案 2 :(得分:0)

(假设您的意思是SQL Server):与SQL Server一起使用的最佳日期格式是ISO 8601:

yyyyMMdd HHmmss。

但是,使用String.Format编写SQL是一种可怕的做法。使用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();