SQL Selecting without parameters? - vb.net

Im trying to select all records from a database table. Each record has a date in it i want to select all records where that date matches todays date
i created a variable called todaydate and used it within the query but i get No value provided for one or more required parameters error. What possible parameters would i use
Here is the code
Any help would be appreciated
Dim todaydate As Date = Date.Today()
If DbConnect() Then
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "Select * from Tbl_Rental Where DateOfHire = todaydate"
'parameters????

You're not using the variable. However, you should always use sql-parameters not concatenate strings(one reason: avoiding SQL-Injection). I'd also suggest to use the Using-statement for the connection and everything else that implements IDisposable:
Using cn As New OleDbConnection(connectionString)
cn.Open()
Using cmd As New OleDbCommand("Select * from Tbl_Rental Where DateOfHire = #DateOfHire", cn)
dim hireDateParameter As new OleDbParameter("#DateOfHire", OleDbType.Date)
hireDateParameter.Value = Date.Today
cmd.Parameters.Add(hireDateParameter)
' ... '
End Using
End Using
If it's always Date.Today you could do that also without a parameter because every database has date functions which return the current date. But since you haven't told us which DB you are using it's hard to show an example.

You need to actually use your variable, not include it as part of the string. Try this:
.CommandText = "Select * from Tbl_Rental Where DateOfHire = '" & todaydate.ToString("dd/MM/yy") & "'"

From a slightly different angle, would it suffice that the date was simply "greater than yesterday"?
.CommandText = "Select * from Tbl_Rental Where DateOfHire >= cast(getdate() as date)"
This strips the time off the date and anything at or later than midnight today is included.

Related

Select value and display in a combobox if the datetimepicker value lies between two extreme dates in a table in database

I am creating an attendance management system in vb.net and using MS access as my database. I created a leave form in which the student on leave has a roll number and his details along with the from date and to date field.
What I'm trying to do is to show all the roll numbers of students in the ComboBox on leave if the DateTimePicker value is in between the to date and from date, the command that I created as MS access query is selecting the from date and to date ie., extreme dates matching with the DateTimePicker value but not showing the values if date is between the to and from date.
this is the code and query:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
con.Open()
Dim cmd1 As New OleDbCommand("Select roll_no From leaves Where semester= " + ComboBox3.SelectedItem + " and (from_date<= #" & DateTimePicker1.Value.ToShortDateString & "# and to_date >= #" & DateTimePicker1.Value.ToShortDateString & "#)", con)
Dim da1 As New OleDbDataAdapter
da1.SelectCommand = cmd1
Dim dt1 As New DataTable
dt1.Clear()
da1.Fill(dt1)
ComboBox4.DataSource = dt1
ComboBox4.DisplayMember = "roll_no"
ComboBox4.ValueMember = "roll_no"
con.Close()
End Sub
Is there any modification in query through which I can get my desired results to get all the roll no if DateTimePicker value is between dates in database?
Well, you probably do want to wrap the code in a using block - that way if you have a error, it will STILL close the connection. Also, it means you don't have to close the connection - a using block ALWAYS will (so, this costs you ONLY one extra line of code, but it more robust - will not leave stray connections open.
Next up:
While everyone warns and suggests to try and avoid string concertation for reasons of SQL injection?
Actually, the BETTER case is that string concatenation is tricky, messy, and you have to remember to use quotes to surround strings, maybe "#" for dates, and for numbers no surrounding delimiters. And one tiny missing single quote or whatever, and your sql is now wrong. So, this is a BETTER case and reason to use parameters - to allow you to write code, and write code that is easer to fix, read, maintain, and even add more parameters to without complex string concatenations.
So, I would suggest this:
Using conn As New OleDbConnection(My.Settings.AccessDB)
Dim strSQL As String =
"Select roll_no From leaves Where from_date >= #cboDate and to_date <= #cboDate " &
"AND semester = #Semester"
Using cmd = New OleDbCommand(strSQL, conn)
cmd.Parameters.Add("#cboDate", OleDbType.DBDate).Value = DateTimePicker1.Value
cmd.Parameters.Add("#Semester", OleDbType.Integer).Value = ComboBox3.SelectedValue
conn.Open()
ComboBox4.DisplayMember = "roll_no"
ComboBox4.ValueMember = "roll_no"
ComboBox4.DataSource = cmd.ExecuteReader
End Using
End Using
And note how I dumped the need for a data adaptor - don't' need it.
And note how I dumped the need for a data table - don't' need it.
However, you do OH SO VERY often need a data table. So, since we humans do things over and over without thinking - memory muscle - then I would suggest that it is ok to create and fill a data table and shove that into the "on leave".
So since we "often" will need a data table, then for the sake of learning, then you could write it this way (so we now learn how to fill a data table).
Using conn As New OleDbConnection(My.Settings.AccessDB)
Dim strSQL As String =
"Select roll_no From leaves Where from_date >= #cboDate and to_date <= #cboDate " &
"AND semester = #Semester"
Using cmd = New OleDbCommand(strSQL, conn)
cmd.Parameters.Add("#cboDate", OleDbType.DBDate).Value = DateTimePicker1.Value
cmd.Parameters.Add("#Semester", OleDbType.Integer).Value = ComboBox3.SelectedValue
conn.Open()
Dim dt1 As New DataTable
dt1.Load(cmd.ExecuteReader)
ComboBox4.DisplayMember = "roll_no"
ComboBox4.ValueMember = "roll_no"
ComboBox4.DataSource = dt1
End Using
End Using
But, either way? Note how I did not have to remember, think about, worry about, and try to figure out the delimiters. Is that a " # " we need for dates, or is that a " ' " we need around the date?
Of course this code would be placed in the timepicker value changed event.

Filter between dates VB.NET and Access database

As the title says, I'm unable to filter an SQL sentence from access database with vb.net
Dim data1 As String = DateTimePicker1.Value.ToShortDateString
Dim data2 As String = DateTimePicker2.Value.ToShortDateString
Dim sql As String = "SELECT totais.* From totais Where totais.data Between #" + data1 + "# And #" + data2 + "#;"
It gives me random values. If i put 1-10(October)-2019 it gives me all the records in system, if i put 12-10(October)-2019 it only gives today's record (doesn't show yesterday and before records). I'm not finding the problem, can you please help?
Thanks
I would use Parameters instead of concatenating a string for the Sql statement. It makes the statement much easier to read and avoids syntax errors.
With OleDb the order that parameters appear in the sql statement must match the order they are added to the parameters collection because OleDb pays no attention to the name of the parameter.
Private Sub OPCode()
Dim sql As String = "SELECT * From totais Where data Between #StartDate And #EndDate;"
Using dt As New DataTable
Using cn As New OleDbConnection("Your connection string"),
cmd As New OleDbCommand(sql, cn)
cmd.Parameters.Add("#StartDate", OleDbType.Date).Value = DateTimePicker1.Value
cmd.Parameters.Add("#EndDate", OleDbType.Date).Value = DateTimePicker2.Value
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
DataGridView1.DataSource = dt
End Using
End Sub
You need to use single quotes and convert type in SQL like this:
SELECT totais.* FROM totais WHERE totais.data Between CDATE('" + data1 + "') And CDATE('" + data2 + "');"
You should use parameters as per Mary's answer BUT for completeness...
Ms/Access requires dates specified as #mm/dd/yy# so your SQL will only work properly where the local date time format is mm/dd/yy. i.e. mostly the US. Otherwise you will have to format your date string.

How to select MONTH() and YEAR() using SELECT query

Basically, I want to run a query to pull data entered into a VB form (specifically MONTH and YEAR).
This is what I currently have:
SELECT * FROM orders WHERE MONTH(date_ordered) = ? AND YEAR(date_ordered) = ? ;
When I run this in my database, it doesn't work. I get no results.
However, if I put it like this:
SELECT * FROM orders WHERE MONTH(date_ordered) = 08 AND YEAR(date_ordered) = 1989;
It works fine and pulls the expected results. Obviously, as I am using a form where the user is supposed to input the 'month' and 'year' themselves, this makes things a bit tricky.
What am I missing here? Cheers for any thoughts.
Note: the date_ordered field is a Date/Time field with a Short Date format.
This may help you..
Dim sql As String = "SELECT * FROM orders WHERE MONTH(date_ordered) = #mon and YEAR(date_ordered) = #year"
Using cn As New SqlConnection("Your connection string here"), _
cmd As New SqlCommand(sql, cn)
cmd.Parameters.Add("#mon", SqlDbType.VarChar, 50).Value = textBox1.text
cmd.Parameters.Add("#year", SqlDbType.VarChar, 50).Value = textBox2.text
Return cmd.ExecuteScalar().ToString()
End Using

VB.NET date format

How do I replace 2014-12-27 with the current date in the statement
Dim cmd As New SqlCommand("Select * from LateComersReport where PDate = '2014-12-27'", conn)
or how can I have the date in the format 'yyyy-mm-dd'in the statement
Dim Tday As Date = Date.Today
First, a date has no format, it has only a value. A date-string can have a format.
Second, always use sql-parameters instead of string concatenation if you build your sql query. That prevents sql-injection or conversion/locatization issues. And always pass the correct type(date is this case) instead of letting the database interpret your argument.
Using cmd As New SqlCommand("Select * from LateComersReport where PDate = #PDate", conn)
cmd.Parameters.Add("#PDate" , SqlDbType.Date).Value = Date.Today ' or SqlDbType.DateTime '
' .. '
End Using
You can simply change your SQL query to this:
"Select * from LateComersReport where PDate = CONVERT(DATE, GETDATE())"
A few things I'd like to point out: date variables, whether in SQL or in .NET, do not have formats. Formatting is only useful/relevant when you are talking about displaying a date, i.e. as a string in a report or in a UI. You shouldn't care how a date is displayed when it's a date value being used in your code.
Also, as a habit, you should use parameters in your SQL statements whenever applicable as opposed to concatenating strings together. For example, if you were to insert your own date value in the query instead of using SQL's built-in GETDATE() function, you would do this:
Dim cmd As New SqlCommand("Select * from LateComersReport where PDate = #MyDateValue", conn)
Dim param As New SqlParameter("#MyDateValue", Now)
cmd.Parameters.Add(param)
The reason for this is string concatenation to build SQL is inherently unsafe due to the risk of SQL injection attacks.

search for a field between two dates in vb.net

My information in database is weak and I do not know how to use queries. I have searched the web and I learned few thing about making queries and I found an example but i do not know how to use it in vb.net.
The query in SQL server will be like this:
select hb from gen where date between 12/6/2014 and 16/6/2014
It works fine, but i don't know how to use it in vb.net
so wrote this line of code and i think my solution will be something like this:
BindingSource1.Filter = String.Format("select hb from gen where date between" & DateTimePicker1.Value & "and" & GENDateTimePicker1.Value)
so what is wrong with this line
If you'd read the documentation then you'd know that the BindingSource.Filter property requires dates to be expressed in the format #M/dd/yyyy#. Also, the String represents just a WHERE clause, not an entire query. You're not using String.Format properly either. Your code should be:
BindingSource1.Filter = String.Format("[Date] BETWEEN #{0:M/dd/yyyy}# AND #{1:M/dd/yyyy}#", DateTimePicker1.Value, GENDateTimePicker1.Value)
Here is an example on how to use your sql query in vb.net:
First, you want to setup your connection string to your database. Next, you can declare a string with the contents of your sql statement. Third, you'll want to setup a using statement that will close the sql connection when it exits. I would also read up on parameterized sql to mitigate attacks on your database.
Dim con As String = (ConfigurationManager.ConnectionStrings("YOURCONNECTIONSTRINGNAME").ConnectionString)
Dim result as String = String.Empty 'set the result to whatever the datatype of hb is in your database
Dim query as String = "select hb from gen where date between '12-6-2014' and '16-6-2014'"
Using conn As New SqlClient.SqlConnection(con)
Try
conn.Open()
Dim command As New SqlClient.SqlCommand(query, conn)
command.Connection = conn
command.CommandType = CommandType.Text
result = command.ExecuteScalar()
conn.Close()
conn.Dispose()
Catch ex As Exception
System.Diagnostics.Debug.WriteLine(ex.Message)
End Try
End Using
this is the solution which i made after hard searching and a lot of lectures in vb.net and SQL server "Excuse me I am a beginner"
Me.BindingSource1.Filter = String.Format(" date <= #{0:M/dd/yyyy}# AND Date >= #{1:M/dd/yyyy}# and hb like'" & TextBox1.Text & "%'", DateTimePicker1.Value, DateTimePicker2.Value)
and "hb" is the name of the field which i want to find
thank you for your time and the fast respond