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.
Related
error overflow varchar
Comm = New SqlCommand("select * from CUSTOMERDETAILS where id='" & TextBox2.Text & "' or aliasname='" & Convert.ToString(TextBox2.Text) & "' ", Conn)
' Comm.Parameters.Add("#id", SqlDbType.Int).Value = TextBox2.Text
Conn.Open()
DATAREADER = Comm.ExecuteReaderenter code here
If DATAREADER.Read Then
ComboBox1.Text = DATAREADER(1)
Conn.Close()
help me???
Your parameter is a string according to your sql command (surrounded by single quotes). therefore you shouldn't be converting this value to an integer.
You could also try changing TextBox2.Text to CInt(TextBox2.Text) if it's not a string.
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
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.
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()
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") & "#";