I am trying to update a DateTime object into a datetime field of a sql (SQL Server 2000) database.
I have the following function
Public Sub Update(ByVal lastlogin as DateTime)
Using slqupdate as SqlCommand = _connection.开发者_如何学GoCreateCommand()
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
Attempting to call it as follows Update(DateTime.Now) produces the following Exception:
Failed to convert parameter value from a DateTime to a Decimal.
I am not sure what I've done wrong, does anybody know?
Try SQLDBType instead of DBType
I found this on the Microsoft 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
The "command.Parameters.Add("@ID", SqlDbType.Int)" part should be an option, stating that it is a datetime parameter?
精彩评论