Trouble converting DateTime (.net) to datetime (SQL server) - vb.net

I'm trying to pass a string (from a text file) - '17/07/99' into a sql server table - the destination is a date column.
the insert is in a string, of the form:
Dim cmd As New SqlCommand(...yada...)
cmd.CommandText = "INSERT INTO my.table (thisDate, ...etc... ) VALUES (#myDate, ...etc...)"
I am adding the parameters to the cmd using:
cmd.Parameters.Add("#myDate", SqlDbType.DateTime).Value = Date.ParseExact("11/11/11", "dd/MM/yy", CultureInfo("en-GB"))
When I come to ExecuteNonQuery
I get cannot convert string to datetime error.
I thought the ParseExact was doing the conversion from string to DateTime??
Do I really need to do a CONVERT in the sql as well as using datetime structures ?!

Try this:
cmd.Parameters.Add("#myDate", SqlDbType.DateTime).Value = new DateTime(2011, 11, 11);
And also see this:
http://msdn.microsoft.com/en-us/library/w2sa9yss(v=vs.110).aspx

just tested this and it works ... you only need to format your date if you want it consistent no matter what culture your OS is otherwise you don't have to do that
you can use this way
Dim d As Date = "17/07/99"
or you can use this way
Dim d As Date = "17.07.99"
if you only have date without time then it doesn't matter what you use
you can either use this
cmd.Parameters.Add("#myDate", SqlDbType.DateTime).Value = d
or this
cmd.Parameters.Add("#myDate", SqlDbType.Date).Value = d
i just tried both versions mixed and no error whatsoever and rows inserted

Try formatting the string before adding it.
Format(YourTimeStringHere, dd-MM-yy)

Related

DateTime.Now.ToString not formatting properly in VB

I need a date to insert into a database, however even though Im formatting it using
Exportedtime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
it still shows up as 3/24/2016 09:25:13 AM? So when I go to insert it into the MSSQL database Im getting the error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The Database field is a datetime field.
Any ideas?
Thanks
Hi guys thanks for the help. #Alexb provided the hint I needed to carry it out.
con = New SqlConnection(constring)
con.Open()
Dim cmd As New SqlCommand("Update Scripts set ExportedOn = #exportTime where scriptID = " & scriptID, con)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#exportTime", SqlDbType.DateTime).Value = time
cmd.ExecuteNonQuery()
con.Close()
Thanks for all the help.
I too faced this format issue in my application. After a detailed research on date time format in MSSQL, i came up with this solution.
"CONVERT(datetime,'" + DateTime.Now.ToString("yyyyMMdd HH:mm:ss") + "',112)"
Use the above string to insert date time value.
Read more on Convert function here - https://msdn.microsoft.com/en-in/library/ms187928.aspx
here is the simple way you can get :)
Dim d As String = "10/05/2016 14:30:06"
MsgBox(CDate(d).ToString("yyyy/MM/dd HH:mm:ss"))

VB.NET date format

How do I replace 2014-12-27 with the current date in the statement
Dim cmd As New SqlCommand("Select * from LateComersReport where PDate = '2014-12-27'", conn)
or how can I have the date in the format 'yyyy-mm-dd'in the statement
Dim Tday As Date = Date.Today
First, a date has no format, it has only a value. A date-string can have a format.
Second, always use sql-parameters instead of string concatenation if you build your sql query. That prevents sql-injection or conversion/locatization issues. And always pass the correct type(date is this case) instead of letting the database interpret your argument.
Using cmd As New SqlCommand("Select * from LateComersReport where PDate = #PDate", conn)
cmd.Parameters.Add("#PDate" , SqlDbType.Date).Value = Date.Today ' or SqlDbType.DateTime '
' .. '
End Using
You can simply change your SQL query to this:
"Select * from LateComersReport where PDate = CONVERT(DATE, GETDATE())"
A few things I'd like to point out: date variables, whether in SQL or in .NET, do not have formats. Formatting is only useful/relevant when you are talking about displaying a date, i.e. as a string in a report or in a UI. You shouldn't care how a date is displayed when it's a date value being used in your code.
Also, as a habit, you should use parameters in your SQL statements whenever applicable as opposed to concatenating strings together. For example, if you were to insert your own date value in the query instead of using SQL's built-in GETDATE() function, you would do this:
Dim cmd As New SqlCommand("Select * from LateComersReport where PDate = #MyDateValue", conn)
Dim param As New SqlParameter("#MyDateValue", Now)
cmd.Parameters.Add(param)
The reason for this is string concatenation to build SQL is inherently unsafe due to the risk of SQL injection attacks.

How to separate Date and time from DateTime method in ASP.Net

I am writing my SQL query to insert date and time and I want to separate date and time from DateTime method now. I want to store them in a table of my database separately. How I could insert them separately, please guide me.
Here is my incorrect query:
string CheckRequest = "select count(*) from Requests where Date='"+DateTime.Now.ToString()+"'";
DateTime variables in .NET are not 'separable' in date and time parts. They always contains the date and the time (hence the name). What you probably need is to query the database using only the Date part of your query. You could reach your result converting your DateTime variable to a string with just the date part using a special formatting pattern for the ToString method when applied to a DateTime variable
string CheckRequest = #"select count(*) from Requests
where Date='" +DateTime.Now.ToString("yyyy-MM-dd")+"';
but this still leaves an open problem.
Passing a formatted string requires that you format it exactly as your database expects it. Failing to accurately represent the string leads to a failure in retrieving records in the datatable.
A better approach is letting your database engine figure out the Date value from a DateTime variable using a parameterized query.
Something like this
string CheckRequest = #"select count(*) from Requests
where Date=#myDate"
using(SqlConnection cn = new SqlConnection(.......))
using(SqlCommand cmd = new SqlCommand(CheckRequest, cn))
{
cn.Open();
cmd.Parameters.Add("#myDate", SqlDbType.Date).Value = DateTime.Now.ToDay;
object result = cmd.ExecuteScalar();
if(result != null)
{
int count = Convert.ToInt32(result);
MessageBox.Show("Record found=" + count.ToString());
}
else
MessageBox.Show("No Record found");
}
Here I am using a parameter of type Date and assign the Now.ToDay (still a DateTime value but with the time equals to 12:00:00 AM) The database engine now knows to use only the Date part and query your table correctly

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

sql from vb cannot convert to date

Hi i'm trying to convert this line to get list of people active over todays date but cannot get it to work
adapter.SelectCommand = New SqlCommand( _
"select * from klijent where convert(varchar,convert(datetime,replace('" & DateTimeUgovora.Value.ToString & "','#','')),111) >= convert(varchar,getdate(),111)", myConn)
error is conversion of varchar data type to a datetime data type resulted in an out-of-range value.
my string that I get from front is
"29.11.2013. 19:41:08"
I searched everywhere and cannot find the answer please help
You should not need to convert the datetime value to a string, because in SQL you can compare datetime values directly. This is much more stable as it doesn't depend on locale settings. I don't fully understand your SELECT clause as even if the comparison works, it will return either all the rows in the table or none.
However, if you want to use the table column Kli_Ugovor_do in your comparison, you can change your statement to this:
adapter.SelectCommand = New SqlCommand( _
"select * from klijent where Kli_Ugovor_do >= getdate()", myConn)
Btw: in your statement you included the value of the combobox by string concatenation. You should get used to including parameters in your statements in order to avoid SQL injection attacks.
So if you want to use the value of the DateTimePicker, your code should look similar to this:
adapter.SelectCommand = New SqlCommand( _
"select * from klijent where Kli_Ugovor_do >= #dt", myConn)
adapter.SelectCommand.Parameters.AddWithValue("#dt", dateTimeUgovora.Value)
I just created a quick console application with the string mention by you. This may be helpful.
Imports System.Globalization
Module Module1
Sub Main()
Dim myDateString As String = "29.11.2013. 19:41:08"
myDateString = myDateString.Replace(".", "")
Dim myDate As DateTime = DateTime.ParseExact(myDateString, "ddMMyyyy HH:mm:ss", CultureInfo.InvariantCulture)
Console.WriteLine(myDate.ToString())
Console.ReadLine()
End Sub
End Module
I created a quick module for tsql as well, maybe it will help:
Declare #dt varchar(20)
set #dt = '29.11.2013. 19:41:08'
select convert(datetime, Replace(#dt, '. ', ' '), 103)