Quantcast
Channel: VBForums - Database Development
Viewing all articles
Browse latest Browse all 2918

OleDbCommand Query Using Parameters Not Quite Working

$
0
0
Hello,

Running VB.net and using an Access MDB as the backend database. Connection string for database is:
Code:

OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0 ;Data Source=db.mdb")
I'm trying to do a select query to get all of the results where StartTime is between two dates. StartTime is a column in the Access DB of type Datetime. It contains both the date and time information, so I'm attempting to use the SQL command DateValue to strip off the time. However, this isn't working when I use parameters with the query.

For example, this doesn't return any results:
Code:

        Dim query As String = "SELECT * FROM Shifts WHERE DateValue(StartTime) >= @startperiod AND DateValue(StartTime) <= @endperiod;"

        Dim pStart As New DateTime(2023, 3, 1)
        Dim pEnd As New DateTime(2023, 3, 15)

        Dim cmd As OleDbCommand = New OleDbCommand(query, cn)

        cmd.Parameters.AddWithValue("@startperiod", pStart)
        cmd.Parameters.AddWithValue("@endperiod", pEnd)

        'run cmd.ExecuteReader, and go through the results, etc

However, if I change the query string to the value of pEnd (without using a parameter), then this successfully returns the results I am looking for:

Code:

        Dim query As String = "SELECT * FROM Shifts WHERE DateValue(StartTime) >= @startperiod AND DateValue(StartTime) <= @endperiod;"

        Dim pStart As New DateTime(2023, 3, 1)
        Dim pEnd As New DateTime(2023, 3, 15)

        query = query.Replace("@endperiod", "#" & pEnd.ToShortDateString & "#")

        Dim cmd As OleDbCommand = New OleDbCommand(query, cn)

        cmd.Parameters.AddWithValue("@startperiod", pStart)

        'run cmd.ExecuteReader, and go through the results, etc

Here is a sample of the database table:
Name:  2023-03-18 12_15_58-Window.png
Views: 49
Size:  5.4 KB

Any ideas what I am doing wrong with the first option?
Attached Images
 

Viewing all articles
Browse latest Browse all 2918

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>