In a booking form, i want to compare the entered date in the textbox(text mode is date) and all the dates in the database. So if there is an order already booked on that day, it will display already booked select another date otherwise it will carry on the form filling.(in vb.net-visual studio 2012)
this is the code
Protected Sub tbdate_TextChanged(sender As Object, e As EventArgs) Handles tbdate.TextChanged
Dim adaptor As New SqlDataAdapter
Dim ds As New DataSet
Try
objConn.Open()
Dim sqlcmd As New SqlCommand("select order_date from bookorder where order_date=' " & tbdate.Text & "'", objConn)
sqlcmd.ExecuteNonQuery()
adaptor.SelectCommand = sqlcmd
adaptor.Fill(ds)
If ds.Tables(0).Rows.Count > 0 Then
Label8.Visible = True
Label8.Text = "Enter different date"
End If
adaptor.Dispose()
ds.Clear()
Catch
e.ToString()
Finally
objConn.Close()
End Try
End Sub
End Class
select * from table where CAST(datecolumn as DATE) = textbox.date
Maybe you have to cast your textbox's date in order to match DB's format...
Use DateTime.ParseExact method
Related
I am trying to do a SQL query that calculates the number of days between two dates from a database.
However an error occurs when I try to search for specific data from the database. Furthermore does anyone know how I could use the sql Query that counts how many days is between two dates in a calculation, which would use data from another table. I have a room type table which has a room price column, and a booking table where I have the arrival date and departure date how could I calculate the total price for the booking.
System.Data.SQLite.SQLiteException: 'unknown error
Insufficient parameters supplied to the command'
Here is what I have so far
Function GetDuration(ID As Integer, fname As String)
Dim dsql As String = "Select Cast ((
JulianDay(Replace(departuredate,'/','-'))
- JulianDay(Replace(arrivaldate,'/','-'))
) As Integer)
from booking INNER JOIN customers on customers.CustomerID = booking.BookingID
where booking.bookingid = #ID or customers.fname LIKE #Fname;"
Using con As New SQLiteConnection(ConStr)
Dim mycmd As New SQLiteCommand(dsql, con)
con.Open()
cmd.Parameters.Add("#Fname", DbType.String).Value = $"%{fname}%"
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
Dim value As Object = mycmd.ExecuteScalar()
txtdurationofstay = value
End Using
End Function
Private Sub IbtnSearch_Click(sender As Object, e As EventArgs) Handles ibtnBSearch.Click
If txtBookingSearchID.Text <> "" Then
Dim SearchID As Integer
If Int32.TryParse(txtBookingSearchID.Text, SearchID) Then
DgvBookings.DataSource = GetData("null", SearchID)
GetDuration(txtBookingSearchID.Text, "null")
Else
MessageBox.Show("Please enter a valid number in the Search box.")
End If
ElseIf txtBsearchFname.Text <> "" Then
DgvBookings.DataSource = GetData(txtBsearchFname.Text, 0)
GetDuration(0, txtBsearchFname.Text)
End If
End Sub
You defined mycmd here:
Dim mycmd As New SQLiteCommand(dsql, con)
but added the parameters to cmd and not to mycmd:
cmd.Parameters.Add("#Fname", DbType.String).Value = $"%{fname}%"
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
and then you execute:
mycmd.ExecuteScalar()
but there are no parameters in mycmd.
In my database, using SQL Server 2014, with a table named TableOberge and with column named Date-In of type Date, and with a second column named Hour-In of type Time(7).
With this query I want to display the records that have reached their dates and times in DatagridView1... but I have failed to display them correctly.
Any Help please:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dbb_Connection()
Using InfoAdapter As New SqlDataAdapter("SELECT * FROM TABLEOBERGE WHERE [DATE_IN] >= CONVERT(date, GETDATE()) AND [HOUR_IN] >= convert(time(0),getDate())", StrCon)
InfoTable = New DataTable
InfoAdapter.Fill(InfoTable)
DataGridView1.DataSource = InfoTable
End Using
End Sub
My code for add record :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dbb_Connection()
Using Command As New SqlCommand With {.Connection = StrCon}
With Command.Parameters
Command.CommandText = "INSERT INTO [TABLEOBERGE] ([ID], [FIRSTNAME], [PHONE], [ADRESSE], [DATE_OUT], [HOUR_OUT], [DATE_IN], [HOUR_IN]) VALUES (#ID, #FIRSTNAME, #PHONE, #ADRESSE, #DATE_OUT, #HOUR_OUT, #DATE_IN, #HOUR_IN)"
.AddWithValue("#ID", SqlDbType.Int).Value = TextBox1.Text
.AddWithValue("#FIRSTNAME", SqlDbType.NVarChar).Value = TextBox2.Text
.AddWithValue("#PHONE", SqlDbType.NVarChar).Value = TextBox3.Text
.AddWithValue("#ADRESSE", SqlDbType.NVarChar).Value = TextBox4.Text
.AddWithValue("#DATE_OUT", SqlDbType.Date).Value = TextBox5.Text
.AddWithValue("#HOUR_OUT", SqlDbType.Time).Value = TextBox6.Text
.AddWithValue("#DATE_IN", SqlDbType.Date).Value = TextBox7.Text
.AddWithValue("#HOUR_IN", SqlDbType.Time).Value = TextBox8.Text
End With
If StrCon.State = ConnectionState.Closed Then StrCon.Open()
If Command.ExecuteNonQuery() = 1 Then
MsgBox("SUCCED ADD", MsgBoxStyle.MsgBoxRtlReading, "SUCCES")
Else
MsgBox("ERROR FATAL", MsgBoxStyle.MsgBoxRtlReading, "ERROR")
End If
StrCon.Close()
End Using
End Sub
http://www.vbforums.com/showthread.php?862331-Display-record-with-condition-of-date-and-time
And Here
https://www.developpez.net/forums/d1851524/dotnet/langages/vb-net/afficher-records-conditions-date-time/
I think you might have the equality comparer turned the wrong way. If you are looking for an expired date (ie. in the past) then that date should be less than the current date.
SELECT *
FROM TABLEOBERGE
WHERE [DATE_IN] <= CAST(getdate() as Date) AND [HOUR_IN] <= CAST(getDate() AS TIME)
IMO your design would be better if you used a single field for your date and time instead of splitting them into 2. DateIn of type DateTime2(7) would be a good fit. There are plenty of SQL functions that allow you to filter based strictly on time or date if this is necessary. It makes writing a query like above simpler.
SELECT * FROM TABLEOBERGE WHERE [DATE_IN] <= GETDATE()
Please any one help me, I just making a micro finance type software, there was a problem I want to show every week data from access database to vb.net datagrid view but don't work my code,
I insert EntryDate Savings Entry Lable Date (lblSavingsEntryDate.Text = Date.Now.ToString("dd/MM/yyyy"))
Here is my Code
Private Sub btnBalanceWeekly_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBalanceWeekly.Click
Dim Sunday = DateTime.Now.AddDays((Today.DayOfWeek - DayOfWeek.Sunday) * -1).ToString("dd/MM/yyyy")
Dim todate = DateTime.Now.AddDays(0).ToString("dd/MM/yyyy")
Try
Dim sqlstr1 As String
sqlstr1 = "SELECT * FROM Receivedtbl WHERE EntryDate BETWEEN '" + Sunday + "' And '" + todate + "'"
Dim da As New OleDbDataAdapter(sqlstr1, conn2)
Dim dt As New DataTable("Receivedtbl")
da.Fill(dt)
dgvBalanceSavings.DataSource = dt
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn2.Close()
Me.BalanceTotalSeavings()
Me.BalanceGrpReceived()
Me.BalanceCusReceived()
End Try
End Sub
Please Help... How can show data in every week.
It's much more secure and safer way using Parameters (DataAdapter will convert in proper way date, datetime format in sql) instead converting date into string, especially because different date formats and avoiding sql injection.
Bellow is example with using Parameters in, let say, source format (in this case date data type) :
Private Sub btnBalanceWeekly_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBalanceWeekly.Click
Dim Sunday = DateTime.Now.AddDays((Today.DayOfWeek - DayOfWeek.Sunday) * -1)
Dim todate = DateTime.Now.AddDays(0)
Try
Dim sqlstr1 As String
sqlstr1 = "SELECT * FROM Receivedtbl WHERE EntryDate BETWEEN #sunday AND #todate;"
Dim da As New OleDbDataAdapter(sqlstr1, conn2)
da.SelectCommand.Parameters.AddWithValue("#sunday", Sunday)
da.SelectCommand.Parameters.AddWithValue("#todate", todate)
Dim dt As New DataTable("Receivedtbl")
da.Fill(dt)
dgvBalanceSavings.DataSource = dt
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn2.Close()
Me.BalanceTotalSeavings()
Me.BalanceGrpReceived()
Me.BalanceCusReceived()
End Try
End Sub
By this way You don't have to worry about date format conversion.
You trying to compare a date (string date) as "dd/MM/yyyy" format and you have a big problem because your query will be like this in runtime :
WHERE EntryDate BETWEEN '11/02/2018' And '12/02/2018'
Result : Tons of strings are between these dates
For example : '11/02/2018','11/03/2018','11/04/2018', even another year like '11/02/2019'
In string compare, early characters always compare first and they are more important in compare system (in this case your 4 chars for year have less priority than month and even day)
Solution :
Use this format for saving your date :
.ToString("yyyy/MM/dd")
So your code should be like this :
Private Sub btnBalanceWeekly_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBalanceWeekly.Click
Dim Sunday = DateTime.Now.AddDays((Today.DayOfWeek - DayOfWeek.Sunday) * -1).ToString("yyyy/MM/dd")
Dim todate = DateTime.Now.AddDays(0).ToString("yyyy/MM/dd")
Try
Dim sqlstr1 As String
sqlstr1 = "SELECT * FROM Receivedtbl WHERE EntryDate BETWEEN '" + Sunday + "' And '" + todate + "'"
Dim da As New OleDbDataAdapter(sqlstr1, conn2)
Dim dt As New DataTable("Receivedtbl")
da.Fill(dt)
dgvBalanceSavings.DataSource = dt
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn2.Close()
Me.BalanceTotalSeavings()
Me.BalanceGrpReceived()
Me.BalanceCusReceived()
End Try
End Sub
But remember you need save your date string with this format too (old dates which already saved in your database)
First and forever turn on Option Strict. Compile Time errors - good, you can fix them. Runtime errors bad, you might not catch them.
Add two DateTimePicker controls to your form and appropriate labels. There are all kinds of properties you can set if the defaults don't suit you.
The following code shows you how to use parameters with your SQL strings. This not only saves you headaches formating your string but could save your database from malicious input.
Private Sub GetSavings()
Dim da As New OleDbDataAdapter
Dim strSQL As String = "SELECT * FROM Receivedtbl WHERE EntryDate BETWEEN #FromDate And #ToDate;"
Dim FromDate As Date = DateTimePicker1.Value.Date
Dim ToDate As Date = DateTimePicker2.Value.Date
If FromDate >= ToDate Then
MessageBox.Show("From date must be earlier than To date.")
Exit Sub
End If
Dim cmd As New OleDbCommand With {
.Connection = conn2,
.CommandType = CommandType.Text,
.CommandText = strSQL}
'Access cares not about the parameter names but about there order
cmd.Parameters.Add("#FromDate", OleDbType.Date).Value = FromDate
cmd.Parameters.Add("#ToDate", OleDbType.Date).Value = ToDate
da.SelectCommand = cmd
'now continue with your .Fill code
End Sub
I've been trying this for some time now,
So in my MS access database i have a
Table named "reservations" and inside the table are
Name(sid,jen)
Roomtype(single,double)
Arrivaldate(3/20/17, 3/20/17 )
Departuredate(3/21/17, 3/21/17)
And in my visual studio form i have
2 labels = lblsingle , lbldouble
1 button named btnok and
Datetimepicker named Datetimepicker1 (properties format set to "Short")
So here is my code:
Private sub Form1_Load
Dim time as DateTime = DateTime.Now
Dim format As String = "MM/d/yyyy"
Datetimepicker1.Text = time.ToString(format)
Private sub btnok_click
Con.open
Dim cmb As new OleDbCommand("SELECT COUNT (*) FROM [reservations] WHERE [Roomtype] = 'Single' AND [Arrivaldate] = " & Datetimepicker1.Text & " ",Con)
Dim dr As OleDbDataReader = cmb.ExecuteReader
Dim userfound As Boolean = False
While dr.Read
userfound = True
lblsingle.text = (dr(0).ToString())
End While
Con.Close()
End Sub
End Class
.
So what i want to happen is when i choose date 3/20/17 in my datetimepicker1. my lblsingle.text should count to "1" because in my database there is a single with the same date as my datetkmepicker1. But the result is "0"......... i really think there is something that makes my datetimepicker1 and the date in my ms access different,,
Please help.... do i need to change time format somewhere?
First your "Private sub btnok_click" will not handle the button click.
To handle "button click" your implementation should be as shown below (proto):
Private Sub button1_Click(sender As Object, e As System.EventArgs) Handles button1.Click
..
..
..
..
End Sub.
Coming to business logic:
When you want to update/increment your label?
Based on the description in your question, you want to update/increment the label as soon as your "DatTimePicker" value is changed.
But in code you are trying to do it in "Ok" button click.
If you want update the label, when you select a date from "datetimepicker", handle below event (proto):
Private Sub DateTimePicker1_ValueChanged(sender as Object, e as EventArgs) _
Handles DateTimePicker1.ValueChanged
..
..
..
..
End Sub
You must handle dates as datetime and not text:
Dim time as DateTime = DateTime.Today
Dim format As String = "yyyy'/'MM'/'/dd"
Datetimepicker1.Value = time
Private sub btnok_click
Con.open
Dim cmb As new OleDbCommand("SELECT COUNT (*) FROM [reservations] WHERE [Roomtype] = 'Single' AND [Arrivaldate] = #" & time.ToString(format) & "# ",Con)
Do not use text representations of date and time - use DateTime for all purposes except rendering output for your users (or serializing as text output like CSV files).
Handling DateTime values for your control
Use the .Value property to get and set your controls value:
Datetimepicker1.Value = DateTime.Now
Handling DateTime values for your database query
Use a (typed) parameter to pass DateTime values to your database query:
Dim cmb As new OleDbCommand("SELECT COUNT (*) FROM [reservations] WHERE [Roomtype] = 'Single' AND [Arrivaldate] = ?", Con)
cmb.Parameters.Add(Datetimepicker1.Value)
OleDbCommand uses positional parameters - that means you need to match the order of your placeholders when adding parameters:
Dim roomtype As String
roomtype = "Single"
Dim cmb As new OleDbCommand("SELECT COUNT (*) FROM [reservations] WHERE [Roomtype] = ? AND [Arrivaldate] = ?", Con)
cmb.Parameters.Add(roomtype)
cmb.Parameters.Add(Datetimepicker1.Value)
Simplify retrieving scalar results like count(*)
If all you try to get is the count(*), you don't need a OleDbDataReader - let your command ExecuteScalar
lblsingle.Text = cmb.ExecuteScalar()
I am using Microsoft Access as my data source in Visual Studio and want to input a query into it to return a value.
Here is my code:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Select * from [Spend]", MyConn)
da.Fill(ds, "Spend")
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
MyConn.Open()
StartMonth = System.DateTime.Now.ToString("01/MM/yyyy HH:mm:ss")
query = "Select Amount from [Spend] WHERE Spend Date >='" & StartMonth & "'"
cmd = New OleDbCommand(query, MyConn)
TotalCost = CInt(cmd.ExecuteScalar())
MyConn.Close()
End Sub
End Class
I am receiving this error:
Syntax error (missing operator) in query expression 'Spend Date >='01/01/2016 13:46:50''
Can anyone help?
For Access, you should use:
StartMonth = System.DateTime.Now.ToString("yyyy'/'MM'/'01 HH:mm:ss")
query = "Select Amount from [Spend] WHERE [Spend Date] >= #" & StartMonth & "#"
I have found an answer to my problem.
If you have a column name separated by a space, such as 'Spend Date'
You MUST enclose it in brackets like this [Spend Date]
Hope this helps.
Try putting the date in # not '
Examples of using dates as criteria in Access queries