2011-05-31 46 views
0

我正在嘗試將DateTime對象更新到sql(SQL Server 2000)數據庫的日期時間字段中。將日期時間更新到sql db中

我有以下功能

Public Sub Update(ByVal lastlogin as DateTime) 

Using slqupdate as SqlCommand = _connection.CreateCommand() 
    sqlupdate.CommandType = CommandType.Text 
    sqlupdate.CommandText = "UPDATE myTable SET LastLogin = @lastlogin WHERE ID = 2" 

    updatelastlogin = sqlupdate.CreateParameter() 
    updatelastlogin.ParameterName = "@lastlogin" 
    updatelastlogin.DbType = SqlDbType.DateTime 
    updatelastlogin.Value = lastlogin 
    slqlupdate.Parameters.Add(updatelastlogin) 

    sqlupdate.ExecuteNonQuery()  
End Using 
End Sub 

嘗試調用它如下更新(DateTime.Now)產生以下例外:

無法參數值從 一個DateTime轉換爲小數。

我不知道我做錯了什麼,有人知道嗎?

+0

@Anthony:修正了錯誤 – 2011-05-31 13:18:05

回答

2

嘗試使用SQLDBType而不是DBType

+0

你是英雄! :)非常感謝:) :) – 2011-05-31 14:21:12

+0

沒問題。當我將示例移植到c#時,我發現問題很快。 – 2011-05-31 14:25:10

0

我發現這對微軟MSDN:

Private Sub UpdateDemographics(ByVal customerID As Integer, _ 
    ByVal demoXml As String, _ 
    ByVal connectionString As String) 

    ' Update the demographics for a store, which is stored 
    ' in an xml column. 
    Dim commandText As String = _ 
    "UPDATE Sales.Store SET Demographics = @demographics " _ 
    & "WHERE CustomerID = @ID;" 

    Using connection As New SqlConnection(connectionString) 
     Dim command As New SqlCommand(commandText, connection) 

     ' Add CustomerID parameter for WHERE clause. 
     command.Parameters.Add("@ID", SqlDbType.Int) 
     command.Parameters("@ID").Value = customerID 

     ' Use AddWithValue to assign Demographics. 
     ' SQL Server will implicitly convert strings into XML. 
     command.Parameters.AddWithValue("@demographics", demoXml) 

     Try 
      connection.Open() 
      Dim rowsAffected As Integer = command.ExecuteNonQuery() 
      Console.WriteLine("RowsAffected: {0}", rowsAffected) 

     Catch ex As Exception 
      Console.WriteLine(ex.Message) 
     End Try 
    End Using 
End Sub 

的 「command.Parameters.Add(」 @ ID 「SqlDbType.Int)」 部分應該是一種選擇,應該說它是一個日期時間參數?