【问题标题】:Select depends on date VB.NET and SQL Server选择取决于日期 VB.NET 和 SQL Server
【发布时间】:2020-06-22 18:07:04
【问题描述】:

我想统计本月和每个月的 PPM 订单数量,这是我的代码,但运行时出现错误

“#”附近的语法不正确

我需要大致了解如何根据日期进行选择,我讨厌使用日期,请帮助我。谢谢

    Dim dtp0 As New DateTimePicker
    Dim dtp1 = dtp0.Value
    Dim count_m As Integer
    Dim cmd1 As New SqlCommand("SELECT count ([id]) FROM [machines] where ppm1 = #" & dtp1.Day & "/" & dtp1.Month & "/" & dtp1.Year & " # and [takhen] is NULL and [irga] is NULL", connsql)
    Dim da1 As New SqlDataAdapter(cmd1)
    Dim dt1 As New DataTable
    da1.Fill(dt1)
    If dt1.Rows.Count > 0 Then
        connsql.Open()
        count_m = Convert.ToInt32(cmd1.ExecuteScalar())
        connsql.Close()
        Label68.Text = count_m.ToString
    End If

【问题讨论】:

  • 您在关闭# 标记之前有一个额外的空间。 " # and [takhen] is NULL
  • 不管语法错误如何,最好为查询使用参数,而不是尝试通过字符串连接来构建 where 条件。将为您节省一大堆头痛
  • 您应该使用参数化查询来传递您的日期值。对于您当前的代码,您认为在 SET DATEFORMAT MDY 生效的服务器上会发生什么?参数化查询避免了像这样的小问题,同时避免了大的 SQL 注入问题。
  • 添加到@AlwaysLearning 的评论,见why parameters are a best practice

标签: sql-server vb.net


【解决方案1】:

鉴于这是您要问的具体问题,我将就如何正确使用字符串连接将日期插入 SQL 代码提供建议,但您绝对不应该这样做。您应该始终使用参数将任何值插入 SQL 代码。 Here 是我自己写的。

对于这个特定问题,您需要使用正确的日期格式,并且有一种比分别插入日、月和年更简单的方法,例如

Dim sql = $"SELECT * FROM MyTable WHERE DateColumn = #{myDTP.Value:M/dd/yyyy}#"

那是使用字符串插值,这是最近几个 VB 版本中最正确的选项。如果您使用的是旧版本,则可以使用String.Format

Dim sql = String.Format("SELECT * FROM MyTable WHERE DateColumn = #{0:M/dd/yyyy}#", myDTP.Value)

如果你想做错了,那么你可以使用连接运算符:

Dim sql = "SELECT * FROM MyTable WHERE DateColumn = #" & myDTP.Value.ToString("M/dd/yyyy") & "#"

【讨论】:

    【解决方案2】:

    仅使用参数传递DateTime 值将避免日期字符串文字出现问题并提供many other benefits too

    代码示例:

    Dim dtp0 As New DateTimePicker
    Dim dtp1 = dtp0.Value
    Dim count_m As Integer
    Dim cmd1 As New SqlCommand("SELECT count ([id]) FROM [machines] where ppm1 = @ppm1 and [takhen] is NULL and [irga] is NULL;", connsql)
    Dim param1 As SqlParameter = cmd1.Parameters.Add("@ppm1", SqlDbType.Date)
    param1.Value = New DateTime(dtp1.Year, dtp1.Month, dtp1.Day)
    Dim da1 As New SqlDataAdapter(cmd1)
    Dim dt1 As New DataTable
    da1.Fill(dt1)
    If dt1.Rows.Count > 0 Then
        connsql.Open()
        count_m = Convert.ToInt32(cmd1.ExecuteScalar())
        connsql.Close()
        Label68.Text = count_m.ToString
    End If
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-19
      • 1970-01-01
      • 2018-04-03
      • 1970-01-01
      • 2018-03-27
      • 2010-12-10
      • 2016-11-29
      • 2017-05-04
      相关资源
      最近更新 更多