Dim data1 As String
Dim conn1 As SqlConnection
Dim cmd1 As New SqlCommand
Dim ada1 As New SqlDataAdapter()
Dim ds1 As New DataSet
data1 = lbldmdate.Text.ToString()
conn1 = New SqlConnection("Persist Security Info=false;User Id=justin;Data Source=ARULJUSTIN\SQLEXPRESS;Initial Catalog=firemaintain;Integrated Security=True;Pooling=False")
conn1.Open()
ada1 = New SqlDataAdapter("select Recordno, uhnumber,uhbuilding,uhlocation from hydrantmaintain WHERE unndate= '" & Today.ToString("dd/mm/yyyy") & "'", conn)
ada1.Fill(ds1)
dgnxtmdates.DataSource = ds1.Tables(0)
I am getting an error: "cannot convert from date to string"
As #Nawful pointed out, you are using "mm" (minutes) instead of "MM" (months) but it also looks like you month and day are reversed. Now, this is dependant upon your region settings for dates and specifically how you configured the SQL server but to avoid these issues, I like to do this for dates:
CONVERT(datetime, '" & Format(Value, "yyyy-MM-dd") & " 00:00:00', 102)
and this for Date and Time:
CONVERT(datetime, '" & Format(Value, "yyyy-MM-ddTHH:mm:ss") & "', 126)
Note, Value is a date or datetime data type.
In your example, it would be something like this:
ada1 = New SqlDataAdapter("select Recordno, uhnumber,uhbuilding,uhlocation from hydrantmaintain WHERE unndate= CONVERT(datetime, '" & Format(Today, "yyyy-MM-dd") & " 00:00:00', 102)", conn)
Hard to point out, but your string formatting should be dd/MM/yy. mm corresponds to minutes component.
Today.ToString("dd/MM/yyyy");
If unndate is the datetime data type in the database, you don't need to convert Today to string when querying the database.
Cause, Today is already a DateTime.
But, if unndate is a string datatype, varchar or nvarchar for example, my only advice is to use the datatype datetime for the unndate value in the first place if you want to query like that.
Related
I need to get the records that will be ended after two days
but always I got an empty datagridview.
I have tried this code:
Dim after2days As Date = Today.Date.AddDays(3)
Dim sqlstr As String = "SELECT * FROM tblvac where vend between " & Today.Date & " and " & after2days & " "
Dim da As New OleDbDataAdapter(sqlstr, Conn)
ds.Reset()
da = New OleDbDataAdapter(sqlstr, Conn)
da.Fill(ds)
dgv.DataSource = ds
Conn.Close()
Why is this happening and how can I fix it?
Access SQL includes functions, Date() and DateAdd(), which can give you the date range you want for your query.
Dim sqlstr As String = "SELECT * FROM tblvac where vend between Date() and DateAdd('d', 3, Date());"
If you prefer to pass date values from your VB.Net code to the db engine, use a parameter query so that you needn't bother about date format and delimiters. Just supply valid Date/Time values for the parameters.
You are building your query as a string and thus need to use the convert to date function... for MS Access its DateValue see http://www.techonthenet.com/access/functions/date/datevalue.php
Try
Dim sqlstr As String = "SELECT * FROM tblvac where vend between
DateValue('" & Today.Date & "') and DateValue('" & after2days & "') "
As commented by HansUp... this solution needs to have the date format as mm/dd/yyyy or yyyy-mm-dd
Dim sql As String = "SELECT * FROM old where inputdate BETWEEN '" + DateTimePicker2.Value.ToShortDateString() + "' AND '" + DateTimePicker3.Value.ToShortDateString() + "';"
Dim dataadapter As New SqlDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "old_table")
connection.Close()
I have 2 DateTimePickers of format Short. In SQL, the column name "inputdate" of DataType: date.
When I choose dates with days <= 12, everything is working fine. When I choose dates with days > 12, I am having this error. I can see it's a matter of day and month but i'm still can't get the solution.
Any help is really appreciated": Conversion failed when converting date and/or time from character string.
I advice you to use the Parameter to use SqlDbType.DateTime and then pass the DateTime directly to the parameter (do not need to convert) , and also avoid SQL injections , like this :
Dim sql As String = "SELECT * FROM old where inputdate BETWEEN #startDate AND #endDate;"
Dim cmd As New SqlCommand(sql, connection)
cmd.Parameters.Add("#startDate", SqlDbType.DateTime).Value = DateTimePicker2.Value
cmd.Parameters.Add("#endDate", SqlDbType.DateTime).Value = DateTimePicker3.Value
Dim dataadapter As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "old_table")
connection.Close()
the output format of ToShortDateString() is not valid for sql server, and sql mixes the days with months.
try this
Dim sql As String = "SELECT * FROM old where inputdate BETWEEN '" + DateTimePicker2.Value.ToString("yyyy-MM-dd") + "' AND '" + DateTimePicker3.Value.ToString("yyyy-MM-dd") + "';"
read this more more information.
Try this:
Dim dt1 as sring = String.Format("{0:yyyy/MM/dd}", Convert.ToDateTime(DateTimePicker2.Value.ToShortDateString()))
Dim dt2 as sring = String.Format("{0:yyyy/MM/dd}", Convert.ToDateTime(DateTimePicker3.Value.ToShortDateString()))
Dim sql As String = "SELECT * FROM old where inputdate BETWEEN '" + dt1 + "' AND '" + dt2 + "';"
Dim dataadapter As New SqlDataAdapter(sql, connection)
The basic solution is that you have to provide date into either mm/DD/YYYY format or in YYYY-MM-DD date format into ms-sql query.
So, before passing date to query convert your date into either mm/DD/YYYY format or in YYYY-MM-DD format.
I'm trying to query the SQL database for all lines where the date is after a date given through user input. I've run into a variety of errors from "incorrect syntax near" when I surround my date with "#" to "arithmetic overflow error converting expression to". My current code looks like this:
inputdate = InputBox("Please enter the starting date (mm/dd/yyyy)")
Debug.Print inputdate
querydate = "(DTG > " & Format(inputdate, "MMDDYYYY") & ")"
select StationID, DTG, CeilingFeet from SurfaceOb where " & querydate & " and StationID = 'NZWD'"
DTG is the column name for the date-time group in the SQL database. Any idea where I am going wrong? I've tried every solution I could find over the past few days without luck. Thank you in advance.
The primary issue is that dates must be enclosed in single-quotes. Here is a complete working example (minus a valid connection string) that should explain how to achieve your objective. Note that you will also want to switch to the ISO date format, in which the order is Year-Month-Day (YYYY-MM-DD).
Sub UpdateRecords()
Dim connection As New ADODB.connection
Dim recordset As New ADODB.recordset
Dim connectionString As String
Dim query As String
Dim inputdate As Date
Dim querydate As String
inputdate = InputBox("Please enter the starting date (mm/dd/yyyy)")
querydate = "(DTG > '" & Format(inputdate, "yyyy-mm-dd") & "')"
query = "select StationID, DTG, CeilingFeet from SurfaceOb where " & querydate & " and StationID = 'NZWD'"
connectionString = "..."
connection.Open connectionString
recordset.Open query, connection
ActiveSheet.Range("A1").CopyFromRecordset recordset
End Sub
Dates for SQL Server should be formatted as a date or date/time, qualified with single-quotes:
Date in ISO unseparated date format
querydate = "(DTG > '" & Format(inputdate, "yyyymmdd") & "')"
Date/Time in ISO 8601 format
querydate = "(DTG > '" & Format(inputdate, "yyyy-mm-ddThh:mm:ss.000") & "')"
Date format for MySQL is YYYY-MM-DD.
Also, as DTG is datetime, you'll need DATE(DTG) > DATE(NOW()) for example - DATE() is a MySQL function that checks only the date portion of a datetime stamp.
Your query should look like this:
querydate = "(DATE(DTG) > " & Format(userinput, "YYYY-MM-DD") & ")"
select StationID, DTG, CeilingFeet from SurfaceOb where " & querydate & " and StationID = 'NZWD'"
I have a DataGridView contains all the spots with (DateStarttasck, TimeStarttasck) and (DateEndtasck, TimeEndtask) made in a given period (StartDate, EndDate), and I try to calculate the number of hours between (DateStarttasck, TimeStarttasck) and (DateEndtasck, TimeEndtask) during the period (StartDate, EndDate)
NB: DateStarttasck, TimeStarttasck are each separated in DateTimePicker
and same thing for (DateEndtasck, TimeEndtask) (StartDate, EndDate)
so I'm looking at first to do a combinaision between Time and date and then calculate the number of hours
Dim sql As String = "select * from task where id_task = " & Textbox1.Text & " and Datetasck Between '" & DateTimePicker1.Text & "' And '" & DateTimePicker2.Text & "';"
command.CommandText = sql
connection.Open()
Dim ds As New DataSet
Dim SQLAdapter As New MySqlDataAdapter(sql, connStr)
SQLAdapter.Fill(ds, "connectString")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "connectString"
DataGridView1.AutoResizeColumns()
connection.Close()
Use DateTime.TryParse to attempt to convert the date string and time string into a single DateTime object, like this:
Dim dateValue As Date
If Date.TryParse(dateString + " " + timeString, dateValue) Then
' Successfully parsed date and time strings into the dateValue object
Else
' Unable to parse date and time strings
End If
Note: dateString is the date piece from the database and timeString is the time piece from the database.
First of all, add both date and time (start with start) and (end with end)
ex: IN C#
DateTime date_Start = DateTime.Parse(StartDate_txt.Text);
DateTime Time_Start = DateTime.Parse(StartTime_txt.Text);
date_Start.AddHours(double.Parse(Time_Start.Hour));
DateTime date_End = DateTime.Parse(EndDate_txt.Text);
DateTime Time_End = DateTime.Parse(EndTime_txt.Text);
date_End.AddHours(double.Parse(Time_End.Hour));
float Diff = date_End.Subtract(date_Start).Hours
i hope you got the idea sorry,it's in c# but hopefully you get the idea and it's same way in vb
I'm using basic date picker for vb.net and oracle as my database. when i insert the date from basic date picker, i got this error >> ORA-01797: this operator must be followed by ANY or ALL
this is my code :
Private Function GetDate(ByVal bdp1 As Date) As DataSet
Dim connectionString As String = "Data Source = ***; User ID =***; Password =**;"
Dim sqlConnection As OracleClient.OracleConnection = New OracleClient.OracleConnection(connectionString)
Dim queryString As String = "select * from smsdw.lot_act where tran_dttm <= ('" & bdp1 & "' , 'MM/DD/YYYY') and tran_dttm > ('" & bdp1 & "', 'MM/DD/YYYY')"
Dim sqlCommand As OracleClient.OracleCommand = New OracleClient.OracleCommand(queryString, sqlConnection)
sqlCommand.CommandTimeout = 0
Dim dataAdapter As OracleClient.OracleDataAdapter = New OracleClient.OracleDataAdapter(sqlCommand)
Dim dataSet As DataSet = New DataSet
dataAdapter.Fill(dataSet)
Return dataSet
End Function
Try, instead:
Dim queryString As String = "select * from smsdw.lot_act where tran_dttm <= :dtm1 and tran_dttm > :dtm2"
Dim sqlCommand As OracleClient.OracleCommand = New OracleClient.OracleCommand(queryString, sqlConnection)
sqlCommand.Parameters.AddWithValue("dtm1",bdp1)
sqlCommand.Parameters.AddWithValue("dtm2",bdp1)
Which a) avoids the possibility of SQL injection, and b) Keeps the date as a date throughout, rather than mangling it to/from a string.
It doesn't fix the logical issue with your query though - where you're trying to find a row where tran_dttm is both "less than or equal" and "greater than" the same value.
Try this ..
Dim queryString As String = "select * from smsdw.lot_act where tran_dttm <= cdate('" & bdp1.Value.ToString & "') and tran_dttm > cdate('" & bdp1.Value.ToString & "')"
Try this:
Dim queryString As String = "select * from smsdw.lot_act where tran_dttm <= '" & bdp1.ToString("MM/dd/yyyy") & "' and tran_dttm > '" & bdp1.ToString("MM/dd/yyyy") & "'"
But for oracle the default datetime format is YYYY-MM-DD. You have three options:
Change the default file format for the one that suits your desires
Use the default format: bdp1.ToString("yyyy-MM-dd")
Use the todate oracle function specifiying the read format:
" to_date('" & bdp1.ToString("MM/dd/yyyy") & "', 'mm/dd/yyyy') "