【问题标题】:How to ensure dates are in correct format for OleDbCommand parameters?如何确保 OleDbCommand 参数的日期格式正确?
【发布时间】:2013-05-08 15:58:19
【问题描述】:

当我对MDB 数据库执行下面的代码时,数据表是空的,但是当我在查询工具中对数据库运行它时,它会返回 2 条记录。

可能是什么问题?

参数的日期格式是否存在问题(即 8/5/13 与 5/8/13)?

Using oDB As OleDbConnection = GetDbConnection()
    Using oCmd As New OleDbCommand("SELECT * " & _
            " FROM Table1, Table2" & _
            " WHERE (Table1.Date BETWEEN @Date1 AND @Date2) AND (Table1.Id IS NULL) AND (Table2.number = Table1.num) AND (Table1.code1 = Table2.code1) ", oDB)
        oCmd.Parameters.AddWithValue("@Date1", Date.Today)
        oCmd.Parameters.AddWithValue("@Date2", Date.Today.AddDays(Me.intDaysAhead))
        oDB.Open()
        dt = New DataTable()
        Using da As OleDbDataAdapter = New OleDbDataAdapter(oCmd)
            da.Fill(dt)
        End Using
    End Using
End Using

【问题讨论】:

  • 如果日期时间格式与正在使用的数据库不匹配,则这些比较将不起作用。使用DateTime.ToString("FormatString") 确保您的 dt 格式相同。 PS:不要将 vb 标记为 C#。
  • table3 怎么样,你想要笛卡尔积吗?
  • @TonyHopkinson:不,已删除。

标签: .net vb.net ms-access ado.net


【解决方案1】:

我认为你是对的。建议指定参数类型OleDbType

 oCmd.Parameters.Add("@Date1", OleDb.OleDbType.Date).Value = Date.Today

【讨论】:

  • 该行无法在我的 Visual Studio 2010 IDE 中编译。
  • 错误信息为:Expression is a value and therefore cannot be the target of an assignment.
  • 我的答案是新版本的代码。现在在VS2010中测试。请不要忘记以类似方式修改“@Date2”的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-15
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 2021-06-05
  • 2020-05-31
  • 2013-09-18
相关资源
最近更新 更多