How to read data from database using datetimepicker value. I have a datetimepicker and a datagridview in my form. I want to get data from Sql databse table with the selected
My NOT RECOMMENDED solution:
Remove the parenthesis and %
characters. Put a space just before the ORDER
(though it is not the cause of your syntax error).
Fix the select in this way:
"SELECT EMP_ID,EMP_NAME,AT_STATUS,AT_REMARK FROM ATTENDANCE WHERE AT_DATE = '" & _
editDate.ToString("yyyy-MM-dd hh:mm:ss") & _
"' ORDER BY EMP_NAME ASC"
What I do recommmend you is to learn to use SQL Parameters.
The query should looks then like this (note the @editDate parameter place-holder inside):
"SELECT
EMP_ID,EMP_NAME,AT_STATUS,AT_REMARK FROM ATTENDANCE WHERE AT_DATE = @editDate ORDER BY EMP_NAME ASC"
.
Then you need just to add the parameters to the SqlCommand
. The easiest way is to do that is to use SqlParameterCollection.AddWithValue.
yourSqlCommand.Parameters.AddWithValue("@editDate", editDate)
A complete sample:
Dim editDate As Date = DTPEDITAT.Value
Using conn As New SqlConnection(YOUR_CONNECTION_STRING_HERE)
Using cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText = "SELECT EMP_ID,EMP_NAME,AT_STATUS,AT_REMARK FROM ATTENDANCE WHERE AT_DATE = @editDate ORDER BY EMP_NAME ASC"
cmd.Parameters.AddWithValue("@editDate", editDate)
adapter.SelectCommand = cmd
adapter.Fill(ds)
For Each row As DataRow In ds.Tables(0).Rows
[do whatever with the result]
Next
End Using
conn.Close()
End Using
From MSDN about Sql Parameters
Command objects use parameters to pass values to SQL statements or stored procedures, providing type checking and validation. Unlike command text, parameter input is treated as a literal value, not as executable code. This helps guard against "SQL injection" attacks, in which an attacker inserts a command into an SQL statement that compromises security on the server. In addition to the security benefits, parameterized commands provide a convenient method for organizing values passed to a data source.