Missing Operator Help VB - vb.net

Syntax Error Missing Operator in query Expression 'doj>=#03/Jan/2016 and 'doj<=#03/Jan/2016'.
SQL = "select * from tbluser Where doj >=#" & DateTimePicker1.Text & " # and <=#" & DateTimePicker2.Text & "#"
acscmd = New OleDbCommand(SQL, acsconn)
acscmd.CommandType = CommandType.Text
acsdr = acscmd.ExecuteReader
If acsdr.Read = True Then
Label1.Text = (acsdr.GetValue(0).ToString())
End If

In this line
SQL = "... Where doj >=#" & DateTimePicker1.Text & " # and <=#" & DateTimePicker2.Text "#"
there isn't a doj field before the <=# part of your string and there is no & symbol to concatenate the last # to the previous string.
Said that, you should forget about this way to query a database.
The correct way is through parameters like here
SQL = "select * from tbluser Where doj >= #p1 and doj <= #p2"
acscmd = New OleDbCommand(SQL, acsconn)
acscmd.Parameters.Add("#p1", OleDbType.Date).Value = DateTimePicker1.Value.Date
acscmd.Parameters.Add("#p2", OleDbType.Date).Value = DateTimePicker2.Value.Date
acsdr = acscmd.ExecuteReader
.....
This query uses parameters, it is not subject to Sql Injection, the parameters are passed with the correct datatype expected by the columns involved in the query, there is no confusion caused by the concatenation in your command text.
EDIT
Following your comment below, if you want to know the number of rows that have a doj value between two dates then you should change your query and introduce the scalar function COUNT
SQL = "select COUNT(*) from tbluser Where doj >= #p1 and doj <= #p2"
acscmd = New OleDbCommand(SQL, acsconn)
acscmd.Parameters.Add("#p1", OleDbType.Date).Value = DateTimePicker1.Value.Date
acscmd.Parameters.Add("#p2", OleDbType.Date).Value = DateTimePicker2.Value.Date
Dim result as Integer = acscmd.ExecuteScalar
.....
The command executes the method ExecuteScalar instead of ExecuteReader because there is only the value calculated by the COUNT function to return and not whole records of data.

Related

How to find field with date range?

So I'm trying to select record with a specific date range ex. 5/21/2019 - 5/30/2019 and put the records into a datagridview.
I'm using Ms. Access and I don't know many things about SQL.
DA = New OleDb.OleDbDataAdapter("SELECT * FROM table where date >= " & DateValue(FirstDate) & " AND date <= " & DateValue(SecondDate) & "", conn)
DS = New DataSet
DS.Clear()
DA.Fill(DS, "table")
DataGridView1.DataSource = DS.Tables("table")
It doesn't give me an error message, but the datagridview doesn't show anything. Thanks for your response
In MS Access, the date delimiter is a hash (#).
So have to change your query to:
"SELECT * FROM table where date >= #" & DateValue(FirstDate) & "# AND date <= #" & DateValue(SecondDate) & "#"
Or you use the between operator:
"Select * FROM table WHERE [Date] Between #" & DateValue(FirstDate) & "# and #" & DateValue(SecondDate) & "#";
A better way to handle this is to simply use parameters which is commonly recommended by many programmers.
da = New OleDb.OleDbDataAdapter("SELECT * FROM table where date >= #StartDate AND date <= #EndeDate ", conn)
'If you show how you declare and set FirstDate and SecondDate we can drop the DateValue function'
da.SelectCommand.Parameters.Add("#StartDate", OleDb.OleDbType.Date).Value = DateValue(FirstDate)
da.SelectCommand.Parameters.Add("#EndeDate", OleDb.OleDbType.Date).Value = DateValue(SecondDate)
ds = New DataSet
DS.Clear()
DA.Fill(DS, "table")
DataGridView1.DataSource = DS.Tables("table")
SELECT ID
FROMTestInfo
WHERE CapturedDate BETWEEN ‘2012-03-27’ AND ‘2012-03-28 ’

Change format of DateTime value

Everybody seems to hate DateTime values.
In my project, I have a SQL SELECT query to find results in the database matching the parameter values.
The code I have is:
Dim where As String = "WHERE [Supp_Code] = #scode " & _
"AND [DateFrom] = #datfrom " & _
"AND [DateTo] = #datto " & _
"AND [Comm_Code] = #ccode " & _
"AND [Customer_Code] = #custcode "
Dim sql As String = "SELECT [Comm_Code], [AqYear] FROM [Acquisition Commission] "
sql &= where & " ORDER BY [AqYear] ASC"
Dim cmd As New OleDb.OleDbCommand(sql, con)
cmd.Parameters.AddWithValue("#scode", cmbSupp.Text.Trim)
cmd.Parameters.AddWithValue("#datfrom", datFrom.Value)
cmd.Parameters.AddWithValue("#datto", datTo.Value)
cmd.Parameters.AddWithValue("#ccode", txtCommCode.Text)
cmd.Parameters.AddWithValue("#custcode", cmbCustomerCode.Text)
Dim daYear As New OleDb.OleDbDataAdapter(cmd)
Dim dsYear As New DataSet
daYear.Fill(dsYear)
The code itself has no issues. The issue is that the DataSet only ever has 0 rows, because the DateTime format of datFrom.Value (which is a DateTimePicker control) is 'MM/dd/yyyy', but in the database it is stored as 'dd/MM/yyyy'.
What's the easiest way of converting it the correct database format before using it as a parameter?
EDIT
Using the comments/answers below, I've adapted my code to the following:
Dim test As DateTime
Dim test2 As DateTime
test = ugDates.ActiveRow.Cells("DateFrom").Value
test = ugDates.ActiveRow.Cells("DateTo").Value
Try
Dim where As String = "WHERE [Supp_Code] = #scode " & _
"AND [DateFrom] = #datfrom " & _
"AND [DateTo] = #datto " & _
"AND [Comm_Code] = #ccode " & _
"AND [Customer_Code] = #custcode "
Dim sql As String = "SELECT DISTINCT [Comm_Code], [AqYear] FROM [Acquisition Commission] "
sql &= where & " ORDER BY [AqYear] ASC"
Dim cmd As New OleDb.OleDbCommand(sql, con)
cmd.Parameters.Add("#scode", OleDbType.VarChar).Value = cmbSupp.Text
cmd.Parameters.Add(New OleDbParameter("#datfrom", OleDbType.Date).Value = test)
cmd.Parameters.Add(New OleDbParameter("#datto", OleDbType.Date).Value = test2)
cmd.Parameters.Add("#ccode", OleDbType.VarChar).Value = txtCommCode.Text
cmd.Parameters.Add("#custcode", OleDbType.VarChar).Value = cmbCustomerCode.Text
But, it gives me the following error on the second parameter:
The OleDbParameterCollection only accepts non-null OleDbParameter type objects, not Boolean objects.
The issue is that the DataSet only ever has 0 rows, because the DateTime format of datFrom.Value (which is a DateTimePicker control) is 'MM/dd/yyyy', but in the database it is stored as 'dd/MM/yyyy'.
That is probably NOT the issue unless you are storing the date as a string. A date is a structure, not a string, and inherently does not have formatting. Formatting is something that is applied to a string. Its similar to a number like an int or decimal. If this field is indeed a string you should revisit your schema and update the type accordingly.
Most likely you are trying to compare a date with time either in the value of the parameter OR in the value of the query.
Use DateValue function to trim the time of the stored database
Use .Date on the date value to only compare the value date
Code:
Dim where As String = "WHERE [Supp_Code] = #scode " & _
"AND DateValue([DateFrom]) = #datfrom " & _
"AND DateValue([DateTo]) = #datto " & _
"AND [Comm_Code] = #ccode " & _
"AND [Customer_Code] = #custcode "
// select either OleDbType.Date or OleDbType.DBDate
cmd.Parameters.Add(new OleDbParameter("#datfrom", OleDbType.Date) With {.Value = datFrom.Value.Date})
cmd.Parameters.Add(new OleDbParameter("#datto", OleDbType.Date) With {.Value = datTo.Value.Date})
The other possible problem is the logic, why not do a between or range check instead of an equality check on DateFrom and DateTo?
"AND DateValue([DateFrom]) >= #datfrom " & _
"AND DateValue([DateTo]) <= #datto " & _
Ideally you would use the same value here for both #datfrom and #datto. The query above would be any item that has a start/end date that span the passed in date parameter.

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

How to put a concatenated data from database to a label

My table goes like this:
| ID | FNAME | LNAME |
My code goes like this:
cmd.CommandText = "SELECT * FROM members WHERE ID = '" & Label18.Text & "'"
dreader = cmd.ExecuteReader()
dreader.Read()
Label3.Text = dreader("CONCAT(fname,' ',lname)").ToString()
cmd.CommandText = "SELECT CONCAT(fname,' ',lname) FROM members WHERE ID = '" & Label18.Text & "';"
Label3.Text = cmd.ExecuteScalar
Note : This makes sense when the select returns a single Cell value
ExecuteScalar() in SqlCommand Object is used for get a single value from Database after its execution. It executes SQL statements or
Stored Procedure and returned a scalar value on first column of first
row in the Result Set. If the Result Set contains more than one
columns or rows , it takes only the first column of first row, all
other values will ignore. If the Result Set is empty it will return a
Null reference.
The easiest way is to just return an additional column from the database itself.
cmd.CommandText = "SELECT *, FullName = fname + ' ' + lname FROM members WHERE ID = '" & Label18.Text & "'"
dreader = cmd.ExecuteReader()
dreader.Read()
Label3.Text = dreader("FullName").ToString()

Get Result (Number) from an sql query

I want to get a simple result from a SQL query to make some calculation
My code :
cn.Open()
cmd.CommandType = CommandType.Text
cmd.CommandText = " SELECT shift1 + shift2 + shift3 as shifts FROM Statistique where nom_produit= '" & ComboBox3.Text & "' and p_date like '" & Date1.Text & "' "
cmd.Connection = cn
Dim st As Integer = cmd.ExecuteScalar
MsgBox(st, 0 + 32, "Your Value !")
cn.Close()
The value of "shifts" is what I need. Now I get just 0
Just to make you know, the query executed successfully in MS Access 2007
I suggest you to change your query to make use of a parameterized query. Keep in mind that a date is not a string. Passing a string for the where clause often will result in an incorrect statement
cn.Open()
cmd.CommandType = CommandType.Text
cmd.CommandText = "SELECT shift1 + shift2 + shift3 as shifts " & _
"FROM Statistique where nom_produit=? AND p_date = ?"
cmd.Parameters.AddWithValue("#p1", ComboBox3.Text)
cmd.Parameters.AddWithValue("#p2", Date1.Value)
cmd.Connection = cn
Dim st As Integer = cmd.ExecuteScalar
MsgBox(st, 0 + 32, "Your Value !")
cn.Close()
Of course this assumes that your field p_date is a DateTime value in MS-Access and that you type a date and TIME value that could be correctly mapped to the field in the database.
EDIT If Date1 is a DateTimePicker then just use the Value property.
The key point here is to pass a parameter with type equal to the field to which it will be applied.
In this way you don't need to worry about conversions or how do you quote the value in a string concatenation.