Error in getting Dates in database (BETWEEN Clause| VB.NET|OLE) - vb.net

before a little time , I used a code to get the dates between 2 dates from the database (column with dates dd/mm/yy) , I think it works nice first time , the code is :
Dim b As New Date
Dim a As Integer
a = Val(tx2.Text)
b = System.DateTime.Today
b = b.AddDays(-a)
MsgBox(b)
Conn.Open()
SQLstr = " Select * from tb where lastvstart BETWEEN #01/01/1800# AND #" & b & "#"
Dim DataAdapter1 As New OleDbDataAdapter(SQLstr, Conn)
DataSet1.Clear()
DataAdapter1.Fill(DataSet1, "Tb")
Conn.Close()
as you see , the code let the user to insert a number and minus it form the date of today , then calculates the date that I want , after that I use BETWEEN Clause to get all dates between them
But now , this code gets some data and overpasses others , I mean some of the dates is between the tow dates but the code never get it , why that happens ?

If you look at the generated SQL string, does it contain the date that you expect? I would assume that the database requires it to follow a specific format (either dd/MM/yyyy or MM/dd/yyyy given the hard coded date in the query). Could it be that your day and month switch places when the string version of the date is created and inserted into your SQL query?
As a side note, I would strongly recommend against concatenating SQL queries together like that. If possible, use parameterized queries instead. That could possibly also remove some type conversion issues.
Update
Here is an example of using a parameterized query over OLE DB to an Access database:
Using connection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=""C:\path\file.mdb""")
Using cmd As New OleDbCommand("select * from tb where lastvstart BETWEEN ? AND ?", connection)
Dim param As OleDbParameter
' add first date '
param = New OleDbParameter()
param.DbType = DbType.Date
param.Value = New DateTime(1800, 1, 1)
cmd.Parameters.Add(param)
'add second date '
param = New OleDbParameter()
param.DbType = DbType.Date
param.Value = DateTime.Today.AddDays(-a)
cmd.Parameters.Add(param)
cmd.Parameters.Add(New OleDbParameter())
connection.Open()
Using adapter As New OleDbDataAdapter(cmd)
Using ds As New DataSet()
adapter.Fill(ds)
Console.WriteLine(ds.Tables(0).Rows.Count)
End Using ' DataSet '
End Using ' OleDbDataAdapter '
End Using ' OleDbCommand '
End Using ' OleDbConnection '

Can you not change the Sqlstr to
SQLstr = " Select * from tb where lastvstart <= '" & b.ToString("dd MMM yyyy") & "'";
EDIT, change based on DB
Use this string and check if it works
SQLstr = " Select * from tb where lastvstart <= #" & b.ToString("dd MMM yyyy") & "#";

Related

SQL filter Date from Label in VB.net

I am stuck with little problem. I have a sql database with DATE column. It is populated from a Label like this: Label1.text = Date.today
and need to show records from one date in datagridwiev. So I need filter date using date from Label. So far I have this:
Public Sub ShowData()
cmd = New SqlCommand("Select * FROM Cisnik WHERE Datum = #" & Label3.Text & "# ", con)
If con.State = ConnectionState.Closed Then con.Open()
myDA = New SqlDataAdapter(cmd)
myDataSet = New DataSet()
myDA.Fill(myDataSet, "Cisnik")
DGV3.DataSource = myDataSet.Tables("Cisnik").DefaultView
End Sub
This code throws : Incorrect syntax near '11.'. The number 11 is a part of European form of date 24.12.2018
The database works OK. Only need this filter problem to solve.
Try:
cmd = New SqlCommand("Select * FROM Cisnik WHERE Datum = '" & cdate(label3.Text).ToString("yyyy-MM-dd") & "'", con)
Your query will be:
Select * FROM Cisnik WHERE Datum = '2018-11-11'
(date example)

Select from SQL Server database with specific range using textbox

Try
conn = New SqlConnection(strcon)
conn.Open()
Dim str As String = "select * from MYTABLE where Year >='#" & Txtfromyear_reprt.Text & "#' and Year <='#" & Txttoyear_reprt.Text & "#'"
da = New SqlDataAdapter(str, conn)
Dim ds As New DataSet
da.Fill(ds, "MYTABLE")
DgvReport.DataSource = ds.Tables("MYTABLE")
da.Dispose()
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
I'm working with my school project but I've encountered a problem in which I can't solve. I wrote this code in my search button but when I click it at runtime, no data is displayed in my datagrid.
What I want is when I click it I want to display all the data from mytable to the Datagrid view using two textboxes. I have two textboxes, txtfromyear and txttoyear and a database column Year with a datatype nvarchar(50).
Please help me, thank you in advance.
Don't use string concatenation to build your sql queries, NEVER!
You are open for sql injection, there is no excuse for it. Instead use sql parameters:
Dim dateFrom as Date
Dim dateTo as Date
Dim validFromDate = Date.TryParse(Txtfromyear_reprt.Text.Trim(), dateFrom)
Dim validToDate = Date.TryParse(Txttoyear_reprt.Text.Trim(), dateTo)
Now exit this method with a meaningful message if the user didn't provide valid dates. You can check validFromDate and validToDate which are booleans. The rest of the code is executed If validFromDate AndAlso validToDate:
Dim str As String = "select * from MYTABLE where Year >= #fromyear and Year <= #toyear"
da = New SqlDataAdapter(str, conn)
da.SelectCommand.Parameters.Add("#fromyear", SqlDbType.DateTime).Value = dateFrom
da.SelectCommand.Parameters.Add("#toyear", SqlDbType.DateTime).Value = dateTo
' now you can use da.Fill(ds, "MYTABLE") safely
I just saw you use varchar to store datetimes. Why? Fix it in the database.

select records which will be ended after 2 days

I need to get the records that will be ended after two days
but always I got an empty datagridview.
I have tried this code:
Dim after2days As Date = Today.Date.AddDays(3)
Dim sqlstr As String = "SELECT * FROM tblvac where vend between " & Today.Date & " and " & after2days & " "
Dim da As New OleDbDataAdapter(sqlstr, Conn)
ds.Reset()
da = New OleDbDataAdapter(sqlstr, Conn)
da.Fill(ds)
dgv.DataSource = ds
Conn.Close()
Why is this happening and how can I fix it?
Access SQL includes functions, Date() and DateAdd(), which can give you the date range you want for your query.
Dim sqlstr As String = "SELECT * FROM tblvac where vend between Date() and DateAdd('d', 3, Date());"
If you prefer to pass date values from your VB.Net code to the db engine, use a parameter query so that you needn't bother about date format and delimiters. Just supply valid Date/Time values for the parameters.
You are building your query as a string and thus need to use the convert to date function... for MS Access its DateValue see http://www.techonthenet.com/access/functions/date/datevalue.php
Try
Dim sqlstr As String = "SELECT * FROM tblvac where vend between
DateValue('" & Today.Date & "') and DateValue('" & after2days & "') "
As commented by HansUp... this solution needs to have the date format as mm/dd/yyyy or yyyy-mm-dd

Converting Date to string with DateTimePicker

Dim sql As String = "SELECT * FROM old where inputdate BETWEEN '" + DateTimePicker2.Value.ToShortDateString() + "' AND '" + DateTimePicker3.Value.ToShortDateString() + "';"
Dim dataadapter As New SqlDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "old_table")
connection.Close()
I have 2 DateTimePickers of format Short. In SQL, the column name "inputdate" of DataType: date.
When I choose dates with days <= 12, everything is working fine. When I choose dates with days > 12, I am having this error. I can see it's a matter of day and month but i'm still can't get the solution.
Any help is really appreciated": Conversion failed when converting date and/or time from character string.
I advice you to use the Parameter to use SqlDbType.DateTime and then pass the DateTime directly to the parameter (do not need to convert) , and also avoid SQL injections , like this :
Dim sql As String = "SELECT * FROM old where inputdate BETWEEN #startDate AND #endDate;"
Dim cmd As New SqlCommand(sql, connection)
cmd.Parameters.Add("#startDate", SqlDbType.DateTime).Value = DateTimePicker2.Value
cmd.Parameters.Add("#endDate", SqlDbType.DateTime).Value = DateTimePicker3.Value
Dim dataadapter As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "old_table")
connection.Close()
the output format of ToShortDateString() is not valid for sql server, and sql mixes the days with months.
try this
Dim sql As String = "SELECT * FROM old where inputdate BETWEEN '" + DateTimePicker2.Value.ToString("yyyy-MM-dd") + "' AND '" + DateTimePicker3.Value.ToString("yyyy-MM-dd") + "';"
read this more more information.
Try this:
Dim dt1 as sring = String.Format("{0:yyyy/MM/dd}", Convert.ToDateTime(DateTimePicker2.Value.ToShortDateString()))
Dim dt2 as sring = String.Format("{0:yyyy/MM/dd}", Convert.ToDateTime(DateTimePicker3.Value.ToShortDateString()))
Dim sql As String = "SELECT * FROM old where inputdate BETWEEN '" + dt1 + "' AND '" + dt2 + "';"
Dim dataadapter As New SqlDataAdapter(sql, connection)
The basic solution is that you have to provide date into either mm/DD/YYYY format or in YYYY-MM-DD date format into ms-sql query.
So, before passing date to query convert your date into either mm/DD/YYYY format or in YYYY-MM-DD format.

select records between two date in vb.net gives error operand type clash

i need to select some records from table Tr_cashbook between two date. the date field is newdt in which i need to compare data and the records should be shown in crystal report named rptCash2. the newdt field has datetime property. here is the code on the command button
bdcon.Open()
Dim QueryString As String
QueryString = "Select * from Tr_Cashbook where (Cast(newdt as date)>= " & DateTimePicker1.Value.ToString("yyyy-MM-dd") & ") and (Cast(newdt as date) <= " & DateTimePicker2.Value.ToString("yyyy-MM-dd") & ")"
Dim Adapter As SqlDataAdapter = New SqlDataAdapter(QueryString, bdcon)
Dim ds As DataSet = New DataSet()
Adapter.Fill(ds, "Tr_Cashbook")
rptCash2.Load()
rptCash2.SetDataSource(ds)
CrystalReportViewer1.ReportSource = rptCash2
bdcon.Close()
but this is not working
when i press the command button it gives error as operand type clash: date is incompatible with int. i am not able to find out where i go wrong . help me with this..
Use parameters instead of hard-coded sql string.
Your parameterized query shoud be:
QueryString = "Select * from Tr_Cashbook where newdt>=#date1 and
newdt<= #date2"
Dim Cmd as new SqlCommand(QueryString,bdcon)
Cmd.Parameters.Add("#date1",SqlDbType.Date).Value=DateTimePicker1.Value
Cmd.Parameters.Add("#date2",SqlDbType.Date).Value=DateTimePicker2.Value
Dim Adapter As SqlDataAdapter = New SqlDataAdapter(Cmd)
Dim ds As DataSet = New DataSet()
Adapter.Fill(ds, "Tr_Cashbook")
You may use BETWEEN AND syntax:
QueryString = "Select * from Tr_Cashbook where newdate BETWEEN #date1 AND #date2"