【问题标题】:Using ADO .NET convert datatime from sql Server to DateTime in VB .NET在 VB .NET 中使用 ADO .NET 将日期时间从 sql Server 转换为 DateTime
【发布时间】:2012-08-20 03:30:35
【问题描述】:

我在 Visual Studio 2005 中使用 VB .NET 语言创建了一个 Web 服务。此 Web 服务通过 ADO .NET 与 Sql Server 上的数据库交互。 使用 ADO .NET,我得到一张带有此代码的表

    conn = New SqlConnection(Utilities.ConnectionString)
    sqlcmd = New SqlClient.SqlCommand()
    sqlcmd.Connection = conn
    sqlcmd.CommandType = CommandType.Text
    sqlcmd.CommandText = "select * from myTable" 
    da = New SqlClient.SqlDataAdapter()
    da.SelectCommand = sqlcmd
    table = New DataTable()
    da.Fill(table)

Utilities 是我创建的用于管理和返回 ConnectionString 的类。 表 myTable 包含多个 String 类型字段和一个名为 LastChangeDate 的 datetime 字段。 我想选择在 myTable 的行中找到的所有日期,所以我使用以下代码:

     Dim d As DateTime 
     For Each row In table.Rows
          d = row.Item("LastChangeDate")
          '
          ' other codes for managing the retuned dates
          '

问题是在这个操作之后 d 包含 NULL 值。

在VB .NET中如何正确地将Item方法返回的日期时间转换为日期时间

【问题讨论】:

  • 如果您的数据库中的 LastChangeDate 列允许 NULL,那么您不能将 NULL 转换为日期。在尝试使用 row.IsNull("LastChangeDate") 将其转换为日期之前,您需要检查 NULL 值
  • 我知道我的数据库在 LastChangeDate 字段中不包含任何 NULL 值。
  • 那么我认为你的意思是 d 包含 Nothing @shahkalpesh 的分析器应该可以帮助你。

标签: sql-server vb.net web-services ado.net datatable


【解决方案1】:
dim isDate as Boolean
dim lastChangeDate as Date

isDate = Date.TryParse(row.Item("LastChangeDate"), lastChangeDate)
If isDate Then
  '** code that should work with the extracted date ...
End If

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多