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()
Related
So as I was running this program, I got this error saying that "ShopperID" is an unknown field although it's indicated in my database in MS Access. It also inserts all the inputs done before that error occurs.
The error I got:
'The INSERT INTO statement contains the following unknown field name: 'ShopperID'. Make sure you have typed the name correctly, and try the operation again.'
Here's my code:
Imports System.Data.OleDb
Public Class acer
Private Sub acer_Load(sender As Object, e As EventArgs) Handles MyBase.Load
conn.Open()
Dim cmd As New OleDbCommand("Select Stocks from vbProduct where ProdID = #pID ", conn)
cmd.Parameters.AddWithValue("#pID", OleDbType.VarChar).Value = "P-1001"
conn.Close()
End Sub
Private Sub btnCart_Click(sender As Object, e As EventArgs) Handles btnCart.Click
Dim sdate As DateTime = Today
Dim shipdate As DateTime
shipdate = sdate.AddDays(5)
shipdate.ToString("mm/dd/yyyy")
sdate.ToString("mm/dd/yyyy")
conn.Open()
Dim cmd As New OleDbCommand("Insert into vbCart(DateTime_Created,DateTime_Checkout,Delivery_Date,ProdID,Cart_ItemsQty,Cart_Items,ShopperID)values
(#created, #checkout, #ship, #pID,#quanti,#items,#UID) ", conn)
cmd.Parameters.AddWithValue("#created", OleDbType.VarChar).Value = sdate
cmd.Parameters.AddWithValue("#checkout", OleDbType.VarChar).Value = sdate
cmd.Parameters.AddWithValue("#ship", OleDbType.VarChar).Value = shipdate
cmd.Parameters.AddWithValue("#pID", OleDbType.VarChar).Value = "P-1001"
cmd.Parameters.AddWithValue("#quanti", OleDbType.Integer).Value = nudqty.Text
cmd.Parameters.AddWithValue("#items", OleDbType.VarChar).Value = "ACER NITRO 5"
cmd.Parameters.AddWithValue("#UID", OleDbType.VarChar).Value = String.Format("{0}{1}, ", sformat, sID)
cmd.ExecuteNonQuery()
TeamAudit("ADD TO CART, ACER NITRO 5, " + String.Format("{0}{1}, ", sformat, sID) + sLast + ", " + sFirst)
conn.Close()
Me.Hide()
example.Show()
End Sub
End Class
I alrerady tried changing its values
Make sure the fields in the "INSERT INTO" are in EXACTLY the same order as the fields in the Access database. I think that is why JayV asked for a screen-grab of the database. This has bit me a few times...Good luck!
how to insert and update data in database(sql server) with single button in vb.net i tried but not get the result.
here is my code.......
Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
Try
Dim reader As SqlDataReader
Dim query As String
Dim n As Integer
n = 0
sqlcom1 = New SqlCommand("select * from mydatabase.masters")
sqlcom1.ExecuteReader()
sqlcom = New SqlCommand("select * from mydatabase.masters")
sqlcom.ExecuteReader()
reader = sqlcom1.ExecuteReader
reader = sqlcom.ExecuteReader
sqlcom = New SqlCommand("Update masters SET EmpName=#EmpName, Age=#Age, Address=#Address where Empid=#Empid", conn)
sqlcom.Parameters.Add("#EmpName", SqlDbType.VarChar).Value = TextBox4.Text
sqlcom.Parameters.Add("#Age", SqlDbType.Int).Value = TextBox3.Text
sqlcom.Parameters.Add("#Address", SqlDbType.VarChar).Value = TextBox2.Text
sqlcom.Parameters.Add("#Empid", SqlDbType.Int).Value = TextBox1.Text
sqlcom1 = New SqlCommand("insert into masters(Empid, EmpName, Age, Address) values(#Empid, #EmpName, #Age, #Address)", conn)
sqlcom1.Parameters.AddWithValue("#Empid", TextBox1.Text)
sqlcom1.Parameters.AddWithValue("#EmpName", TextBox4.Text)
sqlcom1.Parameters.AddWithValue("#Age", TextBox3.Text)
sqlcom1.Parameters.AddWithValue("#Address", TextBox2.Text)
conn.Open()
While reader.Read
n = n + 1
End While
If table.Rows.Count = n Then
sqlcom1.ExecuteNonQuery()
ElseIf table.Rows.Count = n + 1 Then
sqlcom.ExecuteNonQuery()
End If
Catch ex As Exception
MessageBox.Show("error" + ex.Message)
End Try
End Sub
Using block ensures that your connection object is closed and disposed even if there is an error.
Normally I put comments in line but the code got so cluttered that had to move most of them up here. I hope you can figure out where they belong.
Dim reader As SqlDataReader - Unused
Dim query As String - Unused
Integers are automatically initialized to zero
Pass the query and the connection to the constructor of the command.
Your connection string will tell SQL Server what database to use. It is not necessary in the query.
Apparently all you want is the count, not all the data.
This query is exactly the same as sqlcom1
Dim sqlcom As New SqlCommand("select * from mydatabase.masters", cn)
sqlcom.ExecuteReader()
You did this twice
reader = sqlcom1.ExecuteReader
Not necessay, we already retrieved the count
`While reader.Read
n = n + 1
End While`
I made the assumption that table was a DataTable populated at some other time. Using the count as comparison to the count in the table is not a great way to determine if the command is Insert or Update but it might work as long as database and table were not used with a DataAdapter that updated the database.
Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
Try
Dim n As Integer
Using cn As New SqlConnection("Your connection string")
Dim sqlcom1 As New SqlCommand("select Count(*) from masters", cn)
cn.Open()
n = CInt(sqlcom1.ExecuteScalar) 'n is now the number of rows in the database table
Dim sqlcom As New SqlCommand
sqlcom.Parameters.Add("#EmpName", SqlDbType.VarChar).Value = TextBox4.Text
'Age is not a good idea to enter in a database. It changes over time.
'Enter the birth date and calculate the age as needed.
sqlcom.Parameters.Add("#Age", SqlDbType.Int).Value = CInt(TextBox3.Text)
sqlcom.Parameters.Add("#Address", SqlDbType.VarChar).Value = TextBox2.Text
If table.Rows.Count > n Then
'Normally EmpId would be an auto increment (identity) field
'and would NOT be included in an insert.
sqlcom.CommandText = "insert into masters(EmpName, Age, Address) values(#EmpName, #Age, #Address)"
Else
sqlcom.CommandText = "Update masters SET EmpName=#EmpName, Age=#Age, Address=#Address where Empid=#Empid"
sqlcom1.Parameters.Add("#Empid", SqlDbType.Int).Value = CInt(TextBox1.Text)
End If
sqlcom.ExecuteNonQuery()
End Using
Catch ex As Exception
MessageBox.Show("error" + ex.Message)
End Try
End Sub
On second thought, forget the whole thing. Use a DataGridView and a DataAdapter. Then you can just use Update and it will update, insert and delete.
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
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
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