In my program I'm saving date from DateTimePicker into the global variable with
My.Settings.date = dtpDate_do.Value.Date. I'm using this date to compare date from my database but I'm always getting syntax error, no matter what I'm changing.
This is my query:
cmd.CommandText = "SELECT ID, order_date FROM orders WHERE order_date = " & My.Settings.date & " ORDER BY ID DESC"
Dates in my database are stored in EU format with dots - 17.2.2014. Can anyone provide me some help.
Never ever create your query like that. Always and without any exception use parameters. This avoids both SQL-injection attacts and ensures proper formatting of your parameters.
Sorry for not knowing VB.NET, but it should be similar to this:
cmd.CommandText = "SELECT ID, order_date FROM orders WHERE order_date = #Date ORDER BY ID DESC"
cmd.Parameters.AddWithValue("#Date", My.Settings.data)
Explanation: Create your query using #ParamName as a placeholder for your parameters. Then substitute your parameters with values. Make sure to either apply a concrete typed value (i.e. not an object) or/and supply the data type otherwise.
Try to use a parameter in the query like this:
cmd.CommandText = "SELECT ID, order_date FROM orders WHERE order_date = #date ORDER BY ID DESC";
cmd.Parameters.Add(new SqlParameter("#date", dateTimePicker.Value.Date));
Related
I want to update an item's expiration date in MS access but It throws a data type mismatch
This is the code I used to update the item please check this Thanks I tried doing addwithvalue and add("expD",oledbtype.Date) Non works
Query
query = "Update Medicines set BarcodeID = #BarcodeID, Drugs =#DrugName, Dosage = #Dosage, Quantity= #Quantity, Station =#Station, ExpD =#ExpDate, Price=#Price, stckid=#stckid, IsActive='" & ComboBox1.Text & "' where BarcodeID=#BarcodeID"
My parameters
cmd.CommandText = query
cmd.Parameters.AddWithValue("#BarcodeID", txtbarcode.Text)
cmd.Parameters.AddWithValue("#DrugName", txtdrugs.Text)
cmd.Parameters.AddWithValue("#Dosage", txtdosage.Text)
cmd.Parameters.AddWithValue("#Quantity", txtquantity.Text)
cmd.Parameters.AddWithValue("#Station", txtstation.Text)
cmd.Parameters.AddWithValue("#Price", txtprice.Text)
'cmd.Parameters.Add("#ExpD", OleDbType.Date)
'cmd.Parameters.AddWithValue("#ExpDate", dtExpD.Value.Date)
cmd.Parameters.Add("#ExpDate", OleDbType.Date).Value = Me.dtExpD.Value.Date
cmd.Parameters.AddWithValue("#stckid", txtstockid.Text)
cmd.Parameters.Add("#IsActive", OleDbType.LongVarChar)
cmd.Parameters("#IsActive").Value = combocontainer
Thanks
Even though you are using parameter names in your SQL code, the Jet and ACE OLE DB providers ignore those names and substitute values from parameters into the SQL code based on position. That means that you MUST add the parameters to the command in the same order as they appear in the SQL code. You ought to do that regardless but it is essential for Access databases. Your SQL code contains "ExpD =#ExpDate, Price=#Price" but you add parameters like this:
cmd.Parameters.AddWithValue("#Price", txtprice.Text)
cmd.Parameters.Add("#ExpDate", OleDbType.Date).Value = Me.dtExpD.Value.Date
The order is reversed so those values are actually getting used the wrong way around. At least you were alerted by the data type mismatch. If they had been the same type then it would have worked but saved the wrong data to the wrong columns.
When I run the code the line which filled my datatable says that there is no value given for one or more parameters
Order = New OleDb.OleDbDataAdapter("SELECT * FROM Orders WHERE
Driver_ID = " & ID, DBREF)
Order.Fill(dataODtable)
DGVorders.DataSource = dataODtable
The code says this:
An unhandled exception of type 'System.Data.OleDb.OleDbException'
occurred in System.Data.dll
Below is an image link to the database and table it is referencing.
(Database orders table)
If I try run the code without the where statement it runs without crashing.
The field DRIVER_ID is clearly a string, as such you need single quotes around the value you want to use for the WHERE clause.
But that would be wrong for a long list of reasons (Sql Injection, Parsing errors, automatic type conversion with incompatible locales).
So you really need to start using parameterized queries as soon as possible to avoid these misteps
Dim cmdText = "SELECT * FROM Orders WHERE Driver_ID = #drvID"
Order = New OleDb.OleDbDataAdapter(cmdText, DBREF)
Order.SelectCommand.Parameters.Add("#drvID", OleDbType.VarWChar).Value = ID
Order.Fill(dataODtable)
DGVorders.DataSource = dataODtable
Now the query is no more built concatenating together strings pieces (the main source for sql injection hacks) but you create a parameter object of the correct type and pass it to the database engine that will use it when needed.
Another benefit is the more clear code you get. In this case perhaps is not very evident but with more complex queries you will have a more clear understanding of what you are asking to do to the database.
You can try like this:
Order = New OleDb.OleDbDataAdapter("SELECT * FROM Orders WHERE
Driver_ID = '"& ID &"'", DBREF)
Order.Fill(dataODtable)
DGVorders.DataSource = dataODtable
maybe this will be the problem.
if Driver_ID is alphanumeric column, select query should be SELECT * FROM Orders WHERE Driver_ID = '" & ID & "' ;"
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.
I am trying to write stored procedure within my sql command as shown:
Dim tdate As String = Me.PresentDate.Value.ToString("MM-dd-yyyy")
myCommand As New SqlCommand("select c.description as 'provider',b.lastname,
b.firstname, b.middleinitial,convert(varchar(10),b.dob,101) as DOB,
b.chartID,b.sex, d.businessname,d.businessfax from patientappointmentbase as a,
patientlistbase as b,resourcebase as c, locationbase as d where convert(varchar(10),
a.starttime,101) = " & tdate & "
and a.patientid = b.patientid and a.resourceid = c.resourceid and
a.locationid = d.locationid order by provider, lastname, firstname", myConnection)
and when I run this code I'm getting the error as
Conversion failed when converting the varchar value '08/22/1954' to data type int.
You have two primary problems.
The first problem is that the date is being inlined to SQL so that the SQL you are executing looks like:
select ... where convert(varchar(10), a.starttime,101) = 07-07-2013
This is not valid SQL, so you need to wrap the date parameter in single quotes, i.e.
... where convert(varchar(10), a.starttime,101) = '" & tdate & "' and ...
If you wrap it in double-quotes and you have QUOTED_IDENTIFIER set to on, SQL Server will attempt to interpret it as a column name.
The second problem is that you are using two different date formats to compare. Convert using a style of 101 yields a date in the format mm/dd/yyyy. However, you are using a format of mm-dd-yyyy.
This means you are asking SQL server to compare "07/07/2013" with "07-07-2013" which will never be the same. The easiest fix is to change the date format of tdate to match SQL Server's:
Dim tdate As String = Me.PresentDate.Value.ToString("MM/dd/yyyy")
Your concatenated SQL string looks like
convert(varchar(10), a.starttime,101) = 08/22/1954
That's a sequence of division operations that results in a number, not a date.
You want to create a date literal by wrapping the value in quotes.
(or, better yet, use parameters)
I've got a date variable that looks like this:
Dim LogDate As Date = Date.Today.AddDays(-1)
the format comes out like: #4/5/2010#
then it goes into a SQL select query as a WHERE clause. When I debug, the query has changed this to '05/04/2010'. I want it to be in the format '04/05/2010' like it is when declared. Any ideas on how I do this?
Hee is the query:
Dim sqlCmd As New SqlCommand("SELECT TOP (100) PERCENT tblBackup.BackupName,
tblBackupArchive.BackupDate, tblStatus.Status FROM tblStatus INNER JOIN tblBackupArchive ON
tblStatus.StatusID = tblBackupArchive.StatusID INNER JOIN tblBackup ON tblBackupArchive.BackupID =
tblBackup.BackupID INNER JOIN tblClient ON tblBackup.ClientID = tblClient.ClientID WHERE tblBackupArchive.BackupDate = '" & LogDate & "' AND (tblBackupArchive.StatusID = 3) ORDER BY
tblBackupArchive.BackupDate DESC", connection)
-- Jonesy
The best way would be to use a SQLCommand object with a suitable named parameter in the where clause - this would make the formatting of the textual representation of the date totally beside the point...
Another approach, if you're using MS-SQL, would be to use a date in the following format:
Where date = '20100504'
Be careful when using dates though - remember that behind the scenes they are DateTimes...
Martin.