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"))
Related
As the title says, I'm unable to filter an SQL sentence from access database with vb.net
Dim data1 As String = DateTimePicker1.Value.ToShortDateString
Dim data2 As String = DateTimePicker2.Value.ToShortDateString
Dim sql As String = "SELECT totais.* From totais Where totais.data Between #" + data1 + "# And #" + data2 + "#;"
It gives me random values. If i put 1-10(October)-2019 it gives me all the records in system, if i put 12-10(October)-2019 it only gives today's record (doesn't show yesterday and before records). I'm not finding the problem, can you please help?
Thanks
I would use Parameters instead of concatenating a string for the Sql statement. It makes the statement much easier to read and avoids syntax errors.
With OleDb the order that parameters appear in the sql statement must match the order they are added to the parameters collection because OleDb pays no attention to the name of the parameter.
Private Sub OPCode()
Dim sql As String = "SELECT * From totais Where data Between #StartDate And #EndDate;"
Using dt As New DataTable
Using cn As New OleDbConnection("Your connection string"),
cmd As New OleDbCommand(sql, cn)
cmd.Parameters.Add("#StartDate", OleDbType.Date).Value = DateTimePicker1.Value
cmd.Parameters.Add("#EndDate", OleDbType.Date).Value = DateTimePicker2.Value
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
DataGridView1.DataSource = dt
End Using
End Sub
You need to use single quotes and convert type in SQL like this:
SELECT totais.* FROM totais WHERE totais.data Between CDATE('" + data1 + "') And CDATE('" + data2 + "');"
You should use parameters as per Mary's answer BUT for completeness...
Ms/Access requires dates specified as #mm/dd/yy# so your SQL will only work properly where the local date time format is mm/dd/yy. i.e. mostly the US. Otherwise you will have to format your date string.
I am trying to fetch Date, Month and Year separately from date column in Access Database.
I am using following code for it.
I don't know what is the problem with this, but either it shows me error or no data is returned.
I am new to OLEDB so I don't know if it is possible or not.
Please help.
And please show me alternatives if this way is incorrect.
conn_string = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\MHV\Documents\Visual Studio 2012\Projects\UTS\UTS.mdb"
conn = New OleDbConnection(conn_string)
conn.Open()
Grid_string = "SELECT datepart(mm,T_Date) from Transactions"
Grid_cmd = New OleDbCommand(Grid_string, conn)
RW_AD = New OleDbDataAdapter(Grid_cmd)
Grid_DS = New DataSet
Grid_cmd.Connection = conn
Grid_cmd.CommandText = Grid_string
RW_AD.Fill(Grid_DS, "Transactions")
Grid_cmd.ExecuteNonQuery()
DataGridView1.DataSource = Grid_DS.Tables("Transactions").DefaultView
P.S. : Connection and other things are working fine.
It only shows me error when I use datepart().
Can you please try to making datepart interval in quotation?
Grid_string = "SELECT datepart(\"mm\",T_Date) from Transactions"
Using ' instead of " will fix the problem:
Grid_string = "SELECT datepart('mm',T_Date) from Transactions"
Try using m instead of mm
Grid_string = "SELECT datepart('m',T_Date) from Transactions"
Data Type returned is Int16.
Cast to Int16 or you'll get error
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
I am using the below code to insert a date into my SQL dB, but I keep getting the error.
"Operand type clash: int is incompatible with date"
Here is my code:
Using cmdb = New SqlCommand("INSERT INTO Tarrifs (Tarrif, Created_Date) VALUES (#tarrif2, #DateTime)", con)
con.Open()
cmdb.Parameters.AddWithValue("#tarrif2", TextBox1.Text)
cmdb.Parameters.AddWithValue("#DateTime", SqlDbType.Date)
cmdb.ExecuteNonQuery()
con.Close()
End Using
End Using
I think it is because SQL is reading it as a literal string and not a date.
Can anyone help with the correct syntax?
Any help greatly appreciated
SqlDbType is an enum. You're trying to use one of its values (SqlDbType.Date) which is int as parameter value. You need to supply a DateTime value instead:
cmdb.Parameters.AddWithValue("#DateTime", YourDateTimeVariable)
If you try to add current date and time, you don't need to supply it from the code, you can:
use DateTime.Now():
cmdb.Parameters.AddWithValue("#DateTime", DateTime.Now());
or use GETDATE() function from SQL Server:
Using cmdb = New SqlCommand("INSERT INTO Tarrifs (Tarrif, Created_Date) VALUES (#tarrif2, GETDATE())", con)
con.Open()
cmdb.Parameters.AddWithValue("#tarrif2", TextBox1.Text)
cmdb.ExecuteNonQuery()
con.Close()
End Using
It's because you've not supplied a date value for the #DateTime parameter. You've specified a datatype, which is a integer.
Thanks
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)