search for a field between two dates in vb.net - 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

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.

SQL Selecting without parameters?

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.

Datepart function in SQL query not working with OLEDB connection in VB.NET

I am trying to fetch Date, Month and Year separately from date column in Access Database.
I am using following code for it.
I don't know what is the problem with this, but either it shows me error or no data is returned.
I am new to OLEDB so I don't know if it is possible or not.
Please help.
And please show me alternatives if this way is incorrect.
conn_string = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\MHV\Documents\Visual Studio 2012\Projects\UTS\UTS.mdb"
conn = New OleDbConnection(conn_string)
conn.Open()
Grid_string = "SELECT datepart(mm,T_Date) from Transactions"
Grid_cmd = New OleDbCommand(Grid_string, conn)
RW_AD = New OleDbDataAdapter(Grid_cmd)
Grid_DS = New DataSet
Grid_cmd.Connection = conn
Grid_cmd.CommandText = Grid_string
RW_AD.Fill(Grid_DS, "Transactions")
Grid_cmd.ExecuteNonQuery()
DataGridView1.DataSource = Grid_DS.Tables("Transactions").DefaultView
P.S. : Connection and other things are working fine.
It only shows me error when I use datepart().
Can you please try to making datepart interval in quotation?
Grid_string = "SELECT datepart(\"mm\",T_Date) from Transactions"
Using ' instead of " will fix the problem:
Grid_string = "SELECT datepart('mm',T_Date) from Transactions"
Try using m instead of mm
Grid_string = "SELECT datepart('m',T_Date) from Transactions"
Data Type returned is Int16.
Cast to Int16 or you'll get error

SQL Update Column By Adding A Number To Current Int

Simple enough, I can't figure out how to add (that's +) an integer from a textbox to the integer in the SQL Field.
So for example, the SQL Field may have '10' in it and the textbox may have '5' in it. I want to add these numbers together to store '15' without having to download the SQL Table.
The textbox that contains the integer to be added to the SQL integer is tranamount.Text and the SQL Column in the SQL Table is #ugpoints. Please note, without the '+' - which is in the below code and is admittedly wrong- the value of tranamount.Text is added to the Table without an issue, but it simply replaces the original value; meaning the end result would be '5' in the SQL Field.
What would be the proper way to structure this? I've tried the below code, but that clearly doesn't work.
cmd = New SqlCommand("UPDATE PersonsA SET U_G_Studio=#ugpoints WHERE Members_ID=#recevierID", con)
cmd.Parameters.AddWithValue("#recevierID", tranmemberID.Text)
cmd.Parameters.AddWithValue("#ugpoints", + tranamount.Text) '<--- Value to add.
cmd.ExecuteNonQuery()
Newbies question I know, I'm new to SQL in vb.
You have to use the correct sql:
Dim sql = "UPDATE PersonsA SET U_G_Studio=U_G_Studio + #ugpoints WHERE Members_ID=#recevierID"
Also use the correct type with AddWithValue:
Using cmd = New SqlCommand(sql, con)
' use the using-statement to dispose everything that implements IDisposable, so also the connection '
cmd.Parameters.AddWithValue("#ugpoints", Int32.Parse(tranamount.Text))
' .... '
End Using
Take the current value of the U_G_Studio field, add the value of the parameter and reassign to U_G_Studio, but keep in mind that you need to pass the value as an integer because otherwise the AddWithValue will pass a string and you get conversion errors coming from the db.
cmd = New SqlCommand("UPDATE PersonsA SET U_G_Studio=U_G_Studio + #ugpoints " &
"WHERE Members_ID=#recevierID", con)
cmd.Parameters.AddWithValue("#recevierID", tranmemberID.Text)
cmd.Parameters.AddWithValue("#ugpoints", Convert.ToInt32(tranamount.Text))
cmd.ExecuteNonQuery()
The SQL you want is:
"UPDATE PersonsA SET U_G_Studio= (U_G_Studio + #ugpoints) " & _
"WHERE Members_ID=#recevierID"
what about
cmd.Parameters.AddWithValue("#ugpoints", (int)tranamount.Text)
....
cmd = New SqlCommand("UPDATE PersonsA SET U_G_Studio= SET U_G_Studio + #ugpoints WHERE Members_ID=#recevierID", con)
edit1: STEVE WAS FASTER!