Insert date time into database - vb.net

I'm using OleDbCommand to insert a Date/Time field using parameters, and getting an exception stating that "Data type mismatch in criteria expression."
I've identified the parameter causing my issue, and executing the following code causes my error:
insertCmd.CommandText = "INSERT INTO myTable ([ParameterName]) VALUES (?)"
insertCmd.Parameters.AddWithValue("#ParameterName", Now)
insertCmd.Connection = _connection
return insertCmd.ExecuteNonQuery()
Checking out the parameter that's causing the issue, I get the following for parameter {#ParameterName}
ChangeID: 1
DbType: DateTime {6}
Direction: Input {1}
IsNullable: False
Offset: 0
OleDbType: DBTimeStamp {135}
ParameterName: "#ParameterName"
Precision: 0
PrecisionInternal: 0
Scale: 0
ScaleInternal: 0
Size: 0
SourceColumn: ""
SourceColumnNullMapping: False
SourceVersion: Current {512}
Value: #10/9/2014 11:26:15 AM# {Date}
It appears to be recognized as DbType DateTime and the Object inserted into the parameters is a Date object, but It still is telling me that there is a problem with the data type.
Most of the places I've seen this issue have been trying to write a string into a Date/Time field, which I am definitely not doing.

Try using just the Date value since it appears that your database field is a date value only (I'm guessing):
insertCmd.Parameters.AddWithValue("#ParameterName", Now.Date)
or it could be that OleDB is just confused by the type, so set it yourself:
Dim p As New OleDbParameter("#parameterName", OleDbType.Date)
p.Value = Now
insertCmd.Parameters.Add(p)

Related

Option Strict On and DBNull.Value

I've started converting an application of mine to use Option Strict On. I've been doing the CStr,Ctype etc, and it's been going well.
SQLCommand.Parameters.AddWithValue("#TERMINATE", If(IsNothing(txtEarningsTerminated.DateValue), DBNull.Value, txtEarningsTerminated.DateValue))
Then I hit this. The txtEarningsTerminated.DateValue is a custom masked text box. When it's value is Nothing I don't want to store anything in the database. However, it states
Cannot infer a common type, and Option Strict On does not allow 'Object' to be assumed.
When I change DBNull.Value to "" or nothing, the error goes away. However as Nothing, it fails during runtime stating
The parameterized query '(#CONTROL int,#CLIENTCODE nvarchar(10),#NoBill int,#TERMINATE nv' expects the parameter '#TERMINATE', which was not supplied.
I want to put a NULL in the database. This value can be a date and then become a NULL.
How do I translate this so as to not produce an error under Option Strict On?
The reason is because operator If(condition, executeAndReturnIfTrue, executeAndReturnIfFalse) expects that both true and false expressions will return same type.
In your case you return DbNull type if true and String(or some other type you didn't mentioned) if result is false.
If create SqlParameter more explicitly, then you can use next approach:
Dim value As Object = Nothing
If txtEarningsTerminated.DateValue Is Nothing Then
value = DbNull.Value
Else
value = xtEarningsTerminated.DateValue
End If
Dim param As SqlParameter = New SqlParameter With
{
.ParameterName = "#TERMINATE",
.SqlDbType = SqlDbType.VarChar, 'Or use your correct type
.Value = value
}
As mentioned in the comments using AddWithValue will force ADO.NET to decide the sql type automatically for your value, which can lead in different problems. For example everytime you run same query with different values your query plan will be recompiled every time you change value.
You can create extension method for string
Public Module ExtensionsModule
Public Function DbNullIfNothing(this As String) As Object
If this Is Nothing Then Return DBNull.Value
Return this
End Function
End Module
Then use it instead of your "inline If method"
Dim value As String = Nothing
Dim param As SqlParameter = New SqlParameter With
{
.ParameterName = "#TERMINATE",
.SqlDbType = SqlDbType.VarChar,
.Value = value.DbNullIfNothing()
}
So the answer was obvious and in the error. I just had to encase the DBNull.Value in a Ctype Object
CType(DBNull.Value, Object)
And then the code would compile just fine.
Here's one way to do it (assuming you're using stored procedures in your database):
In the stored procedure you're calling, set the date input parameter to equal null, making it an optional field with a default value of null (#terminate DATETIME = NULL).
That way, if you don't include that parameter in your procedure call, the procedure won't fail.
Set the default value of the date field to DateTime.MinValue so it always has some value. Then you can test to see if it is equal to a date other than DateTime.MinValue. If it is a valid date value, add the line to include the date parameter to the procedure call. If it is equal to DateTime.MinValue, don't add the parameter to the call.

Conversion from string "M" to type 'Integer' is not valid

I am having an issues with conversion of values that I am trying to reference via a field that I want to format from an ERP System. I am unable to convert all of my values because they are being pulled out as strings, no matter if variables are set to integer or string. What am I doing that would cause this error, should variables be defined a different way?
Public Class Class1
Inherits erp.Rule
Public Overrides Function Execute() As erp.RuleResult
Dim Result As New RuleResult
Try
Dim date_recieved As Date
Dim month As String
Dim period As String
Dim Year1 As String
Dim Year As String
date_recieved = Data.Fields.GetFieldByAlias("date_received").FieldValue
month = Format(date_recieved, "M").ToString
Year = Data.Fields.GetFieldByAlias("yearAR").FieldValue
period = Data.Fields.GetFieldByAlias("periodAR").FieldValue
If period = month Then
If Year = Year1 Then
Exit Function
Else
MessageBox.Show("Date received does not match year", "Invalid Input")
End If
Else
MessageBox.Show("Date received does not match period", "Invalid Input")
End If
Catch ex As Exception
Result.Message = ex.Message
End Try
Result.Success = True
Return Result
End Function
Format does not accept a string parameter, by you passing "M" it is trying to convert the datatype you supply to the datatype the function accepts and since a string does not implicitly cast to an integer an error occurs
To format a Date type to various formats of string you just use your date variable and its subsequent .ToString() method with your formatting rules as an argument of .ToString()
Here is a link to the msdn explaining all the possible formatting options: https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1

Data type mismatch when inserting record

I've this piece of code for inserting records into an Access table.
LastUpdated field is defined as Date/Time at database level. It fails when inserting giving the error
Data type mismatch in criteria expression
I'm using parameterized query which avoid problems with formatting values and it's very weird because I've the same code (with more parameters) to insert records on another table on which LastUpdated is defined in the same way and it's working fine.
Any idea?
SqlQuery = "INSERT INTO History (ActivityID, LastUpdated) VALUES (#p1,#p2)"
With sqlcommand
.CommandText = SqlQuery
.Connection = SQLConnection
.Parameters.AddWithValue("#p1", IDAct)
.Parameters.AddWithValue("#p2", DateTime.Today)
End With
result = sqlcommand.ExecuteNonQuery()
If (result = 1) Then
LabelWarning.Text = "Activity filled"
LabelWarning.BackColor = Color.ForestGreen
LabelWarning.Visible = True
ButtonSave.Visible = False
ButtonBack.Visible = False
ButtonOK.Visible = True
BlockControls()
End If
Maybe the problem is linked to parameter placeholder.
This MSDN doc states that OleDbCommand does not support named parameter (only positional) and the correct placeholder should be "?" and not "#p1".
https://msdn.microsoft.com/en-us/library/yy6y35y8%28v=vs.110%29.aspx
Edit
It turned out in comments that the placeholder have not to be so strictly adherent to the doc syntax. Only the order has to be absolutely preserved.
Explicitly declaring the parameter type however seemed to do the trick:
.Parameters.Add("#p2", OleDbType.DBTimeStamp)
.Parameters("#p2").Value = DateTime.Today

Argument matching parameter 'text' cannot convert from 'DBNull' to 'String'

Trying to import records from an Access database file and display the records in a listview (in Visual Basic). It works 50% of the time, but seems to crash stating:
An unhandled exception of type 'System.Reflection.AmbiguousMatchException' occurred in Microsoft.VisualBasic.dll
Additional information: Overload resolution failed because no Public 'Add' can be called with these arguments:
'Public Overrides Function Add(text As String) As System.Windows.Forms.ListViewItem':
Argument matching parameter 'text' cannot convert from 'DBNull' to 'String'.
'Public Overrides Function Add(value As System.Windows.Forms.ListViewItem) As System.Windows.Forms.ListViewItem':
Argument matching parameter 'value' cannot convert from 'DBNull' to 'ListViewItem'.
The code in question is the following:
ds.Clear()
LVResults.Items.Clear()
con.ConnectionString = dbProvider & dbSource
con.Open() 'Open connection to the database
sqlstatement = "SELECT * FROM records WHERE checkoutdate is NULL"
da = New OleDb.OleDbDataAdapter(sqlstatement, con)
da.Fill(ds, "allmembers") 'Fill the data adapter
con.Close()
Dim recordCount, x As Short
recordCount = 0
x = 0
recordCount = ds.Tables("allmembers").Rows.Count
With ds.Tables("allmembers")
Do Until x = recordCount
LVResults.Items.Add(.Rows(x).Item(0))
LVResults.Items(x).SubItems.Add(.Rows(x).Item(1))
LVResults.Items(x).SubItems.Add(.Rows(x).Item(2))
LVResults.Items(x).SubItems.Add(.Rows(x).Item(3))
LVResults.Items(x).SubItems.Add(.Rows(x).Item(4))
x = x + 1
Loop
End With
Knowing me it's something really obvious but do appreciate the help :)
The most annoying this is that it works sometimes, but others it'll throw up the error.
The error message is pretty self-explanatory to be honest - some of the fields contain null values, which VB won't auto-convert to empty strings or zeros. One solution would be to edit the SQL statement to explicitly avoid returning nulls:
SELECT IIf(Surname Is Null, '', Surname), IIf(Forename Is Null, '', Forename),
IIf(SomeIntField Is Null, 0, SomeIntField) FROM records WHERE CheckoutDate Is Null

Declare Time - 'Conversion from type 'Timespan' to type 'integer' is not valid'

I declare my dates as the following in my code:
Dim DeliveryDate as Date
But i am now trying to declare time however i keep getting an error because i cannot get the type correct. I tried the following but get the following error: "Conversion from type 'Timespan' to type 'integer' is not valid".
Dim DeliveryTime as DateTime
Dim DeliveryTime as Integer
In my database the DeliveryTime type is set to Time(7) so i would assume there should be 'Time' which i could use to declare it, but there isnt. What is the correct type i should be using?
Here is my exact code. There error is Input string was not in correct format:
GraphDate4 = String.Empty
DeliveryProducts = "{ name: 'DeliveryProducts', data: ["
If DataReader4.HasRows Then
While DataReader4.Read
Dim DevTime As Timespan = DataReader4("DeliveryTime")
GraphDate4 += """" + DevilTime.ToString("d") + ""","
DeliveryProducts += DataReader4("DeliveryProducts").ToString() + ","
End While
End If
On the client-code side of things (your vb.net code), the Date data type is really an alias for the DateTime data type, which includes a component for both date and time in the same value.
But here, it sounds like maybe you just need a TimeSpan data type, and use TimeSpan's FromSeconds() or FromMilliseconds() methods to construct it.