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.
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 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.
I have this code
Dim conex As SqlConnection = New SqlConnection(conxst)
Dim caixa As Integer = ComboBox1.SelectedItem
Dim verdat As Date = DateTimePicker1.Text
Dim verdat1 As Date = "05/07/2012"
conex.Open()
Dim ds As New DataSet
Dim dt As New DataTable
ds.Tables.Add(dt)
Dim da As New SqlDataAdapter("select codigo,data,horario from alteraca where data = '" & verdat1 & "' ", conex)
da.Fill(dt)
this code work when verdat1 is in the format "mm/dd/yyyy" , how i convert the date from mine datetimepicker (dd/mm/yyyy) to the format "mm/dd/yyyy" to place in the statment??? Thanks.
You shouldn't use string representation of a value when you already have binary representation.
Dim dt As New DataTable
Using conex As New SqlConnection(conxst)
conex.Open()
Using cmd As New SqlCommand("select codigo, data, horario from alteraca where data = #data", conex)
cmd.Parameters.AddWithValue("#data", DateTimePicker1.Value)
Using da As New SqlDataAdapter(cmd)
da.Fill(dt)
End Using
End Using
End Using
With
verdat1.ToString("MM/dd/yyyy")
You can select how the date is converted to a string.
Also, you can set the dateTimePicker Custom Format as you wish :
dateTimePicker1.Format = DateTimePickerFormat.Custom
dateTimePicker1.CustomFormat = "MM/dd/yyyy"
In sql query
-use to_date to convert String to date
-and to char for reverse
In your case
select codigo,data,horario from alteraca where data = to_date('" & verdat1 & "','dd/mm/yyyy') ", conex
here 'dd/mm/yyyy' is format of your variable...
Actually, a better (and safer way) to do the query is to use Parameters and Using statements. The Using statement automatically closes the connection, commands and adapter.
Dim caixa As Integer = ComboBox1.SelectedItem
Dim verdat As Date = DateTimePicker1.Text
Dim verdat1 As Date = "05/07/2012"
Dim ds As New DataSet
Dim dt As New DataTable
Using conex as New SQLConnection(conxst)
conex.Open()
Using cmdex as New SQLCommand("select codigo,data,horario from alteraca where data = #DATE " , conxst)
cmdex.Parameters.AddWithValue("#DATE",verdat1)
Using da As New SqlDataAdapter(cmdex)
da.Fill(dt)
End Using
End Using
End Using
You can convert the date like this:
verdat1.ToString("MM/dd/yyyy")
you can use DateTimePicker1.value. It is easily solve
i need to select some records from table Tr_cashbook between two date. the date field is newdt in which i need to compare data and the records should be shown in crystal report named rptCash2. the newdt field has datetime property. here is the code on the command button
bdcon.Open()
Dim QueryString As String
QueryString = "Select * from Tr_Cashbook where (Cast(newdt as date)>= " & DateTimePicker1.Value.ToString("yyyy-MM-dd") & ") and (Cast(newdt as date) <= " & DateTimePicker2.Value.ToString("yyyy-MM-dd") & ")"
Dim Adapter As SqlDataAdapter = New SqlDataAdapter(QueryString, bdcon)
Dim ds As DataSet = New DataSet()
Adapter.Fill(ds, "Tr_Cashbook")
rptCash2.Load()
rptCash2.SetDataSource(ds)
CrystalReportViewer1.ReportSource = rptCash2
bdcon.Close()
but this is not working
when i press the command button it gives error as operand type clash: date is incompatible with int. i am not able to find out where i go wrong . help me with this..
Use parameters instead of hard-coded sql string.
Your parameterized query shoud be:
QueryString = "Select * from Tr_Cashbook where newdt>=#date1 and
newdt<= #date2"
Dim Cmd as new SqlCommand(QueryString,bdcon)
Cmd.Parameters.Add("#date1",SqlDbType.Date).Value=DateTimePicker1.Value
Cmd.Parameters.Add("#date2",SqlDbType.Date).Value=DateTimePicker2.Value
Dim Adapter As SqlDataAdapter = New SqlDataAdapter(Cmd)
Dim ds As DataSet = New DataSet()
Adapter.Fill(ds, "Tr_Cashbook")
You may use BETWEEN AND syntax:
QueryString = "Select * from Tr_Cashbook where newdate BETWEEN #date1 AND #date2"
before a little time , I used a code to get the dates between 2 dates from the database (column with dates dd/mm/yy) , I think it works nice first time , the code is :
Dim b As New Date
Dim a As Integer
a = Val(tx2.Text)
b = System.DateTime.Today
b = b.AddDays(-a)
MsgBox(b)
Conn.Open()
SQLstr = " Select * from tb where lastvstart BETWEEN #01/01/1800# AND #" & b & "#"
Dim DataAdapter1 As New OleDbDataAdapter(SQLstr, Conn)
DataSet1.Clear()
DataAdapter1.Fill(DataSet1, "Tb")
Conn.Close()
as you see , the code let the user to insert a number and minus it form the date of today , then calculates the date that I want , after that I use BETWEEN Clause to get all dates between them
But now , this code gets some data and overpasses others , I mean some of the dates is between the tow dates but the code never get it , why that happens ?
If you look at the generated SQL string, does it contain the date that you expect? I would assume that the database requires it to follow a specific format (either dd/MM/yyyy or MM/dd/yyyy given the hard coded date in the query). Could it be that your day and month switch places when the string version of the date is created and inserted into your SQL query?
As a side note, I would strongly recommend against concatenating SQL queries together like that. If possible, use parameterized queries instead. That could possibly also remove some type conversion issues.
Update
Here is an example of using a parameterized query over OLE DB to an Access database:
Using connection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=""C:\path\file.mdb""")
Using cmd As New OleDbCommand("select * from tb where lastvstart BETWEEN ? AND ?", connection)
Dim param As OleDbParameter
' add first date '
param = New OleDbParameter()
param.DbType = DbType.Date
param.Value = New DateTime(1800, 1, 1)
cmd.Parameters.Add(param)
'add second date '
param = New OleDbParameter()
param.DbType = DbType.Date
param.Value = DateTime.Today.AddDays(-a)
cmd.Parameters.Add(param)
cmd.Parameters.Add(New OleDbParameter())
connection.Open()
Using adapter As New OleDbDataAdapter(cmd)
Using ds As New DataSet()
adapter.Fill(ds)
Console.WriteLine(ds.Tables(0).Rows.Count)
End Using ' DataSet '
End Using ' OleDbDataAdapter '
End Using ' OleDbCommand '
End Using ' OleDbConnection '
Can you not change the Sqlstr to
SQLstr = " Select * from tb where lastvstart <= '" & b.ToString("dd MMM yyyy") & "'";
EDIT, change based on DB
Use this string and check if it works
SQLstr = " Select * from tb where lastvstart <= #" & b.ToString("dd MMM yyyy") & "#";