【问题标题】:Compare date from textbox with date in database in ASP.NET using C#使用 C# 在 ASP.NET 中将文本框中的日期与数据库中的日期进行比较
【发布时间】:2017-01-15 17:10:31
【问题描述】:

我正在尝试比较我在 DD.MM.YYYY 格式的文本框中输入的日期,但出现错误。

string txt = "select count(*) from cont where Data_deschiderii < " + Convert.ToDateTime(TextBox1.Text).ToString("DD.MM.YYYY");

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();

SqlCommand cmd = new SqlCommand(txt, conn);
int x = Convert.ToInt32(cmd.ExecuteScalar().ToString());
Response.Write(x);

我该怎么做?我在互联网上找不到任何东西

【问题讨论】:

    标签: c# asp.net sql-server date


    【解决方案1】:

    最好的方法是开始使用准备好的参数化查询。它们确保正确进行比较,并防止 SQL 注入攻击的可能性。

    您的代码将被重写如下:

    string txt = "select count(*) from cont where Data_deschiderii < @compareDate;"; 
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    conn.Open();
    SqlCommand cmd = new SqlCommand(txt, conn);
    cmd.Parameters.Add("@compareDate", SqlDbType.Date);
    cmd.Parameters["@compareDate"].Value = TextBox1.Text;
    int x = Convert.ToInt32(cmd.ExecuteScalar().ToString());
    Response.Write(x);
    

    也就是说,我假设您的数据库字段 Data_deschideriidate 数据类型形式。

    【讨论】:

    • 当然,请记住对所有 SQL 命令使用参数化查询。没有它们,您就会面临 SQL 注入攻击。通过简单地使用参数化查询,您可以完全摆脱该攻击向量。此外,您还可以获得确保所有比较都正确输入的额外好处。它还使代码更具可读性。
    【解决方案2】:

    您需要将日期时间转换为 SQL 可以理解的内容。

    var formattedDate = Convert.ToDateTime(TextBox1.Text).ToString("yyyy-MM-dd HH:mm:ss");
    

    然后在查询中使用formattedDate

    【讨论】:

    • 它不起作用,我收到“00 附近的语法错误”错误
    • 您的查询中的其他内容很可能不正确。我会检查查询的其余部分,例如字段和表格
    【解决方案3】:

    您应该将日期时间转换为时间跨度,然后以秒为单位比较该时间跨度。在 SQL 中,您可以使用 DateDiff 函数进行相同的转换。

    【讨论】:

      【解决方案4】:

      试试这个。

      try
      {
        DateTime Date1= Convert.ToDateTime(TextBox1.Text).ToString("yyyy-MM-dd HH:mm:ss");
        DateTime Date2 = Convert.ToDateTime(TextBox2.Text).ToString("yyyy-MM-dd HH:mm:ss");
        if (Date1 > Date2) 
        {
          Your Code...
        }
      }
      catch (Exception ex)
      {
          MessageBox.Show(ex.Message);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-12
        • 1970-01-01
        • 2022-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多