Datepart function in SQL query not working with OLEDB connection in VB.NET - sql

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

Related

Filter between dates VB.NET and Access database

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.

SQL Selecting without parameters?

Im trying to select all records from a database table. Each record has a date in it i want to select all records where that date matches todays date
i created a variable called todaydate and used it within the query but i get No value provided for one or more required parameters error. What possible parameters would i use
Here is the code
Any help would be appreciated
Dim todaydate As Date = Date.Today()
If DbConnect() Then
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "Select * from Tbl_Rental Where DateOfHire = todaydate"
'parameters????
You're not using the variable. However, you should always use sql-parameters not concatenate strings(one reason: avoiding SQL-Injection). I'd also suggest to use the Using-statement for the connection and everything else that implements IDisposable:
Using cn As New OleDbConnection(connectionString)
cn.Open()
Using cmd As New OleDbCommand("Select * from Tbl_Rental Where DateOfHire = #DateOfHire", cn)
dim hireDateParameter As new OleDbParameter("#DateOfHire", OleDbType.Date)
hireDateParameter.Value = Date.Today
cmd.Parameters.Add(hireDateParameter)
' ... '
End Using
End Using
If it's always Date.Today you could do that also without a parameter because every database has date functions which return the current date. But since you haven't told us which DB you are using it's hard to show an example.
You need to actually use your variable, not include it as part of the string. Try this:
.CommandText = "Select * from Tbl_Rental Where DateOfHire = '" & todaydate.ToString("dd/MM/yy") & "'"
From a slightly different angle, would it suffice that the date was simply "greater than yesterday"?
.CommandText = "Select * from Tbl_Rental Where DateOfHire >= cast(getdate() as date)"
This strips the time off the date and anything at or later than midnight today is included.

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"))

How to select MONTH() and YEAR() using SELECT query

Basically, I want to run a query to pull data entered into a VB form (specifically MONTH and YEAR).
This is what I currently have:
SELECT * FROM orders WHERE MONTH(date_ordered) = ? AND YEAR(date_ordered) = ? ;
When I run this in my database, it doesn't work. I get no results.
However, if I put it like this:
SELECT * FROM orders WHERE MONTH(date_ordered) = 08 AND YEAR(date_ordered) = 1989;
It works fine and pulls the expected results. Obviously, as I am using a form where the user is supposed to input the 'month' and 'year' themselves, this makes things a bit tricky.
What am I missing here? Cheers for any thoughts.
Note: the date_ordered field is a Date/Time field with a Short Date format.
This may help you..
Dim sql As String = "SELECT * FROM orders WHERE MONTH(date_ordered) = #mon and YEAR(date_ordered) = #year"
Using cn As New SqlConnection("Your connection string here"), _
cmd As New SqlCommand(sql, cn)
cmd.Parameters.Add("#mon", SqlDbType.VarChar, 50).Value = textBox1.text
cmd.Parameters.Add("#year", SqlDbType.VarChar, 50).Value = textBox2.text
Return cmd.ExecuteScalar().ToString()
End Using

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