vb.net SQL date to time conversion issue - sql

The error is: Conversion failed when converting date and/or time from character string.
Basically I'm trying to make it so that when someone clicks a location in a list box it increments the correct field in a Stats table by 1 to say that they clicked the location. I've been trying to solve this for a while now and can't get anywhere. My date is in date format, and so is the Date field in my Stats table. My code can be seen below.
Dim Current As String
Dim Check As String
Dim objCmd2 As Object
Dim iCount As Integer
Dim tDate As Date
Current = LocBox.SelectedItem
Check = LocList.FindString(Current)
If Check > -1 Then
MsgBox("You have already selected this place to visit")
Else
LocList.Items.Add(Current)
ObjDataReader.Close()
tDate = Date.Today
MessageBox.Show(tDate)
tDate = tDate.ToString()
objCmd2 = New SqlCommand("SELECT " & Replace(Current, " ", "_") & " FROM Stats WHERE Date = '" & tDate & "'", objConn)
ObjDataReader = objCmd2.ExecuteReader
If ObjDataReader.HasRows Then
ObjDataReader.Read()
If ObjDataReader(0) Is DBNull.Value Then
iCount = 0
Else
iCount = ObjDataReader(0)
End If
Else
iCount = 0
End If
objCmd = New SqlCommand("INSERT INTO Stats(Date," & Replace(Current, " ", "_") & ") Values('" & tDate.Date & "'," & iCount & " )", objConn)
ObjDataReader.Close()
objCmd.ExecuteNonQuery()
objConn.Close()
Thanks in advance.
The issue comes in with the second SQL statement I think. I don't understand why adding a date into a date field would be an issue, I've tried adding it as a string which didn't work. Thanks for all the answers so far.

As Martin points out this is probably the best choice:
int colnum = ConvertColumnNameToNumber(Current)
objCmd2 = New SqlCommand("SELECT "+colnum.ToString()+" FROM Stats WHERE [Date] = #inDate", objConn)
objCmd2.Parameters.Add("#inDate",SqlDbType.DateTime).value = tDate
Not tested or compiled might have typos.
Note the use of colnum above. Because you can't use parameters for column names you have to use the column number. If you have code that returns an integer as a return value you can protect against injection (it can only a number).

I'm going to guess the issue is here: MessageBox.Show(tDate)
You need to convert the date to a string using tDate.ToString or whatever other method you want.
Are you getting compile errors? I always code with Option Strict On, and your code would definitely bring up errors where you are not converting variables.

I may be off base but you have tDate as a Date variable type and then your trying to send it a string, you can just use tDate.ToString() in your SqlCommand lines and not convert it first.

Try Removing the apostrophes from around tdate so that it is...
objCmd2 = New SqlCommand("SELECT " & Replace(Current, " ", "_") & " FROM Stats WHERE Date = " & tDate, objConn)
and
objCmd = New SqlCommand("INSERT INTO Stats(Date," & Replace(Current, " ", "_") & ") Values(" & tDate.Date & "," & iCount & " )", objConn)

Related

Change format of DateTime value

Everybody seems to hate DateTime values.
In my project, I have a SQL SELECT query to find results in the database matching the parameter values.
The code I have is:
Dim where As String = "WHERE [Supp_Code] = #scode " & _
"AND [DateFrom] = #datfrom " & _
"AND [DateTo] = #datto " & _
"AND [Comm_Code] = #ccode " & _
"AND [Customer_Code] = #custcode "
Dim sql As String = "SELECT [Comm_Code], [AqYear] FROM [Acquisition Commission] "
sql &= where & " ORDER BY [AqYear] ASC"
Dim cmd As New OleDb.OleDbCommand(sql, con)
cmd.Parameters.AddWithValue("#scode", cmbSupp.Text.Trim)
cmd.Parameters.AddWithValue("#datfrom", datFrom.Value)
cmd.Parameters.AddWithValue("#datto", datTo.Value)
cmd.Parameters.AddWithValue("#ccode", txtCommCode.Text)
cmd.Parameters.AddWithValue("#custcode", cmbCustomerCode.Text)
Dim daYear As New OleDb.OleDbDataAdapter(cmd)
Dim dsYear As New DataSet
daYear.Fill(dsYear)
The code itself has no issues. The issue is that the DataSet only ever has 0 rows, because the DateTime format of datFrom.Value (which is a DateTimePicker control) is 'MM/dd/yyyy', but in the database it is stored as 'dd/MM/yyyy'.
What's the easiest way of converting it the correct database format before using it as a parameter?
EDIT
Using the comments/answers below, I've adapted my code to the following:
Dim test As DateTime
Dim test2 As DateTime
test = ugDates.ActiveRow.Cells("DateFrom").Value
test = ugDates.ActiveRow.Cells("DateTo").Value
Try
Dim where As String = "WHERE [Supp_Code] = #scode " & _
"AND [DateFrom] = #datfrom " & _
"AND [DateTo] = #datto " & _
"AND [Comm_Code] = #ccode " & _
"AND [Customer_Code] = #custcode "
Dim sql As String = "SELECT DISTINCT [Comm_Code], [AqYear] FROM [Acquisition Commission] "
sql &= where & " ORDER BY [AqYear] ASC"
Dim cmd As New OleDb.OleDbCommand(sql, con)
cmd.Parameters.Add("#scode", OleDbType.VarChar).Value = cmbSupp.Text
cmd.Parameters.Add(New OleDbParameter("#datfrom", OleDbType.Date).Value = test)
cmd.Parameters.Add(New OleDbParameter("#datto", OleDbType.Date).Value = test2)
cmd.Parameters.Add("#ccode", OleDbType.VarChar).Value = txtCommCode.Text
cmd.Parameters.Add("#custcode", OleDbType.VarChar).Value = cmbCustomerCode.Text
But, it gives me the following error on the second parameter:
The OleDbParameterCollection only accepts non-null OleDbParameter type objects, not Boolean objects.
The issue is that the DataSet only ever has 0 rows, because the DateTime format of datFrom.Value (which is a DateTimePicker control) is 'MM/dd/yyyy', but in the database it is stored as 'dd/MM/yyyy'.
That is probably NOT the issue unless you are storing the date as a string. A date is a structure, not a string, and inherently does not have formatting. Formatting is something that is applied to a string. Its similar to a number like an int or decimal. If this field is indeed a string you should revisit your schema and update the type accordingly.
Most likely you are trying to compare a date with time either in the value of the parameter OR in the value of the query.
Use DateValue function to trim the time of the stored database
Use .Date on the date value to only compare the value date
Code:
Dim where As String = "WHERE [Supp_Code] = #scode " & _
"AND DateValue([DateFrom]) = #datfrom " & _
"AND DateValue([DateTo]) = #datto " & _
"AND [Comm_Code] = #ccode " & _
"AND [Customer_Code] = #custcode "
// select either OleDbType.Date or OleDbType.DBDate
cmd.Parameters.Add(new OleDbParameter("#datfrom", OleDbType.Date) With {.Value = datFrom.Value.Date})
cmd.Parameters.Add(new OleDbParameter("#datto", OleDbType.Date) With {.Value = datTo.Value.Date})
The other possible problem is the logic, why not do a between or range check instead of an equality check on DateFrom and DateTo?
"AND DateValue([DateFrom]) >= #datfrom " & _
"AND DateValue([DateTo]) <= #datto " & _
Ideally you would use the same value here for both #datfrom and #datto. The query above would be any item that has a start/end date that span the passed in date parameter.

Removing first character from a column if it starts with 0

I have an oracle table, a_abc that have three columns (name, ID and address). The data for this table will be extracted from a txt file. How to remove the first character in ID column if it starts with number '0'. I need a VB solution. This is what Ive done so far now
Private Sub ReadData()
Dim rowvalue As String
Dim cellvalue(20) As String
Dim header As String = "ID"
Dim streamReader As IO.StreamReader = New IO.StreamReader("D:\local_costctr.txt")
'Reading CSV file content
While streamReader.Peek() <> -1
rowvalue = streamReader.ReadLine()
cellvalue = rowvalue.Split("|") 'check what is ur separator
ConnectOracle()
mySQLcmd.Connection = myConn
If SQL.Length > 0 Then
SQL.Replace(SQL.ToString, "")
End If
SQL.Append("insert into a_abc (name ,ID ,address) ")
SQL.Append(" values ('" & cellvalue(0) & "' ,'" & cellvalue(1) & "','" & cellvalue(2) & "') ")
Console.WriteLine(header)
Console.WriteLine(header.Trim({"0"c}))
Try
mySQLcmd.CommandText = SQL.ToString
mySQLcmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error " & ex.Message.ToString)
End Try
End While
End Sub
If there is more than one leading zero, I want all of them removed.
The ltrim function should do the trick:
SELECT name, LTRIM(id, '0'), address
FROM a_abc
EDIT:
Now that the question was edited, I see you refer inserting the data, not querying it. The same solution could be applied on an insert too though:
SQL.Append("insert into a_abc (name ,ID ,address) ")
SQL.Append(" values ('" & cellvalue(0) & "', LTRIM(" & cellvalue(1) & ", '0'), '" & cellvalue(2) & "') ")
While you are extracting the data from the txt-file and you come across the ID-field:
For Each line As String In IO.File.ReadAllLines("yourpath")
If "myID".Substring(0, 1) = "0" Then
'take the "myID" without the leading 0
"myID".Substring(1)
End if
Next
Depending on your case you might need Null-checks etc...
Edited for your code:
Replace cellvalue(1) in the SQL.append by:
IIF(cellvalue(1).Substring(0, 1) = "0",cellvalue(1).Substring(1),cellvalue(1))

select records which will be ended after 2 days

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

Incorrect syntax near 's'. Unclosed quotation mark after the character string

I'm using a query to pull data from an SQL database, at times the last dropdown im using to get the record i'm looking for has a single quote, when it does I get the following error: Incorrect syntax near 's'. Unclosed quotation mark after the character string
This is the code I have:
Using objcommand As New SqlCommand("", G3SqlConnection)
Dim DS01 As String = DDLDS01.SelectedItem.Text
Dim State As String = DDLState.SelectedItem.Text
Dim Council As String = DDLCouncil.SelectedItem.Text
Dim Local As String = DDLLocal.SelectedItem.Text
Dim objParam As SqlParameter
Dim objDataReader As SqlDataReader
Dim strSelect As String = "SELECT * " & _
"FROM ConstitutionsDAT " & _
"WHERE DS01 = '" & DS01 & "' AND STATE = '" & State & "' AND COUNCIL = '" & Council & "' AND LOCAL = '" & Local & "' AND JURISDICTION = '" & DDLJurisdiction.SelectedItem.Text & "' "
strSelect.ToString.Replace("'", "''")
objcommand.CommandType = CommandType.Text
objcommand.CommandText = strSelect
Try
objDataReader = objcommand.ExecuteReader
DDLJurisdiction.Items.Add("")
While objDataReader.Read()
If Not IsDBNull(objDataReader("SUBUNIT")) Then
txtSubUnit.Text = (objDataReader("SUBUNIT"))
End If
If Not IsDBNull(objDataReader("DS02")) Then
lblDS02.Text = (objDataReader("DS02"))
End If
If Not IsDBNull(objDataReader("LEGISLATIVE_DISTRICT")) Then
txtALD.Text = (objDataReader("LEGISLATIVE_DISTRICT"))
End If
If Not IsDBNull(objDataReader("REGION")) Then
txtRegion.Text = (objDataReader("REGION"))
End If
If DDLState.SelectedItem.Text <> "OTHER" Then
If Not IsDBNull(objDataReader("UNIT_CODE")) Then
txtUnitCode.Text = (objDataReader("UNIT_CODE"))
End If
End If
End While
objDataReader.Close()
Catch objError As Exception
OutError.Text = "Error: " & objError.Message & objError.Source
Exit Sub
End Try
End Using
Not all records contain a single quote, only some, so i'd need something that would work if a single quote is present or not.
Thanks.
Your problem is this line here:
strSelect.ToString.Replace("'", "''")
This is changing your WHERE clause from something like
WHERE DS01 = 'asdf' AND ...
To:
WHERE DS01 = ''asdf'' AND ...
You need to do the replace on the individual values in the where clause, not on the whole select statement.
What you should really be doing is using a parameterized query instead.
Update: added same link as aquinas because it's a good link
Use parameterized queries, and only EVER use parameterized queries. See: How do I create a parameterized SQL query? Why Should I?

Sql query to update new values to column Visual Basic

This is my code:
Dim job As String = TextBoxJobNum.Text
Dim idws As Integer
sqlQuery = "UDATE Equipment SET JobHistory = JobHistory+'" & job & "' WHERE ID = '" & idws & "'"
Dim sqlCmd1 As New SqlCommand(sqlQuery, sqlConn)
If sqlConn.State = ConnectionState.Closed Then sqlConn.Open()
For Each row As DataGridViewRow In DataGridViewEquip.Rows
idws = CInt(row.Cells(0).Value)
sqlCmd1.ExecuteNonQuery()
Next
If sqlConn.State = ConnectionState.Open Then sqlConn.Close()
I get the error "Syntax error near '=' " I have searched everywhere but cant seem to find the
correct Syntax for this line. Any help would be greatly appreciated.
Looks to me like you are just missing a "P" in the word "UPDATE"
sqlQuery = "UPDATE Equipment SET JobHistory = JobHistory+'" & job & "' WHERE ID = '" & idws & "'"
Also I would recommend not setting parameters using string concatenation, but instead use parameters on a SqlCommand object. The reason for this is reducing potential problems such as additional escaping (if the "job" variable contains a "'" for example) or SQL injection.