Sql Update command VB.Net With Date - sql-server

I have an SQL update command that I can't get to work. i want it to update the fields where the date is equal to the current date. It works for my INSERT and SELECT statements. But I get a missing operator error when using it for my Delete statement below.
Cmd.Connection = conn
Cmd.CommandText = "UPDATE tbl_Expenditure SET E_Stock =" & NewEStock & "," & "E_Total =" & ETotal & "WHERE [E_Date] = #" & thisMonth & "/" & Day & "/" & thisYear & "#;"
Cmd.ExecuteNonQuery()
Ive tried searching this site as well as others and can't seem to find an answer.
This is my error
Syntax error (missing operator) in query expression '95WHERE [E_Date] = #4/1/2015#'.
Thanks for any help

Using conn As New SqlConnection("connection string here"), _
cmd As New SqlCommand("UPDATE tbl_Expenditure SET E_Stock = #Stock, E_Total = #Total WHERE [E_Date] = #Date;", conn)
'Guessing at column types here
cmd.Parameters.Add("#Stock", SqlDbType.Int).Value = NewEStock
cmd.Parameters.Add("#Total", SqlDbType.Decimal, 8, 2).Value = ETotal
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = New DateTime(thisYear, thisMonth, Day)
cmd.ExecuteNonQuery()
End Using
This fixes a HUGE security issue in the code, it has a performance benefit in allowing Sql Server to cache your query plan, and it solves your problem in that is makes it much easier to spot silly syntax mistakes like the missing space in front of the WHERE clause.

Related

SQL parameters not returning any results

Following code is not returning any results:
search = "'%" & Request.QueryString("itemname") & "%'"
Set cmd = Server.CreateObject("ADODB.COMMAND")
Set cmd.ActiveConnection = conn
sql = ""
sql = sql & "DECLARE #search varchar;"
sql = sql & "SET #search = ?;"
sql = sql & "SELECT ID, itemname, itemtype FROM vw_items WHERE itemname LIKE #search"
cmd.CommandText = sql
cmd.CommandType = adCmdText
response.write("<strong>You searched for:</strong> " & search & "<br /><br
/>")
cmd.Parameters.Append cmd.CreateParameter("#search", adVarchar, adParamInput, 50, search)
set rs = cmd.Execute
else
search = null
strSQL2 = "SELECT * FROM vw_items"
set rs = server.CreateObject("ADODB.Recordset")
rs.open strSQL2,conn
end if
I've seen this answer: ADO parameterised query not returning any result and tried fixing mine but no luck
Any help would be much appreciated
When using ADODB.Command the provider infers the data type based off the Parameters collection that is setup before calling the Execute() method.
As you are passing in as
search = "'%" & Request.QueryString("itemname") & "%'"
in effect when the SQL is executed by the provider it will look like (because it already knows the Parameter is a VARCHAR data type already)
WHERE itemname LIKE ''%youritemname%''
When you actually want it to be
WHERE itemname LIKE '%youritemname%'
This means the current query is doing a LIKE for the physical string '%youritemname%' rather than doing an actually pattern matching query.
The fix is simple, remove the single quotes from the search variable, like so;
search = "%" & Request.QueryString("itemname") & "%"
Useful Links
A: How to use ASP variables in SQL statement (useful tips when working with the ADODB.Command object)

VBA sql query based off combobox

I've been searching hard the past few days and have come across numerous examples that outline what I'm trying to do. However, I can't seem to get this working. I have a combobox that populates data (a company name) from a table when the form initializes. I then want to take the value chosen in the combo box and run another query to cross reference an id number in that same table.
Private Sub CommandButton1_Click()
Dim myCn As MyServer
Set myCn = New MyServer
Dim rs As ADODB.recordset
Set rs = New ADODB.recordset
Dim sqlStr As String
Dim CompField As String
'CompField = ComboBox1.Value
sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE [company] = '" & ComboBox1.Text & "'"
'sqlStr = "Select DISTINCT [company] FROM client;"
' sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE [company] = " & UserForm1.ComboBox1.Value & ";"
'sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE [company] = " & UserForm1.ComboBox1.Text & ";"
'sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE [company] = 'Company XYZ';"
'sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE company = " & CompField & ""
rs.Open sqlStr, myCn.GetConnection, adLockOptimistic, adCmdText
MsgBox sqlStr
'MsgBox ComboBox1.Value
'MsgBox rs(0)
rs.Close
myCn.Shutdown
Set rs = Nothing
Set myCn = Nothing
End Sub
Currently with the combobox value encased in single quotes i get the entire sql string returned. If I remove the single quotes I get a syntax error referencing part of the combobox value. All other efforts have resulted in run-time errors that have led me nowhere.
I know my query works because I've tested it in SQL Studio and if I hard code a text value in this code I also get the Account ID I'm looking for. Not sure what I'm missing here.
Well I figured it out. I was expecting to be able to MsgBox the variable assigned to the SQL query and see my results. But it doesn't work that way. I had to use ADO GetString method for that and assign another variable. Oh and you were right about escaping, I had to add delimters to properly handle the ComboBox value in the query which ultimately looked like this
sqlStr = "SELECT DISTINCT [acct_no] FROM client WHERE [company] = " & Chr(39) & Me.ComboBox1.Value & Chr(39)
Thanks for your help on this

How to use SQL parameters with IF conditions and what datatype is equal to the NVARCHAR. OLeDB, VB.NET

So my question actually has more than 2 parts but all linked with protecting my application against SQL injection.
Lately I am rebuilding my application to make it SQL injection proof. My application is written in VB.NET and I am using Parameters.Add to protect the queries.
UPDATE first question:
Found out that the NVARCHAR datatype is equal to the WChar datatype in OLEDB. When hovering over WChar it says in the description it is WSTR.
I am having a few questions though of which I cant find the answer on the web.
The first one, and I guess the easiest one is what the datatype in OleDB is of the NVARCHAR. When doing some research I found this link https://msdn.microsoft.com/en-us/library/ms130984.aspx which states that in OleDB the DBTYPE_WSTR datatype is the same as the NVARCHAR (which I am using in my t-SQL server). However when adding parameters in my VB application there is no such datatype available (WSTR). Some options are the VarChar, VarWChar, WChar, LongVarChar, LongVarWChar.
The question is, which one is the right one? I assume it is VarChar.
-------UPDATED UNTIL HERE-----
The second question is about how to handle parameters when a IF condition is involved in the query (see the example below).
sSQL1 = "SELECT [Omschrijving], [Nummer], [OrderType], [Orderdatum] FROM [Orders] WHERE [OrderDatum]>dateadd(""ww"",-4,GetDate()) "
If sOrderType <> "" Then
sSQL1 &= "AND ([OrderType]=""" & sOrderType & """)"
End If
sSQL1 &= "ORDER BY [Orders].[Nummer] DESC;"
lstOrder.Items.Clear()
Try
OpenConn()
cmd = New OleDbCommand(sSQL1, cn)
dr = cmd.ExecuteReader
While dr.Read()
lstOrder.Items.Add(dr("nummer") & " - " & dr("Omschrijving"))
End While
Catch
Debug.Print(sSQL1)
MsgBox("Error: " & sSQL1)
End Try
dr.Close()
CloseConn()
How should I rewrite this with using parameters? Do I need to instantiate the cmd = New OleDbCommand(sSQL1, cn) in the if condition together with the Parameters.Add ? But I guess this would also mean I have to open the connection earlier?
I thought about rewriting in something like this:
OpenConn()
sSQL1 = "SELECT [Omschrijving], [Nummer], [OrderType], [Orderdatum] FROM [Orders] WHERE [OrderDatum]>dateadd(""ww"",-4,GetDate()) "
If sOrderType <> "" Then
sSQL1 &= "AND ([OrderType]=?)"
cmd = New OleDbCommand(sSQL1, cn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#OrderType", OleDbType.VarChar).Value = sOrderType
Else
cmd = New OleDbCommand(sSQL1, cn)
End If
sSQL1 &= "ORDER BY [Orders].[Nummer] DESC;"
lstOrder.Items.Clear()
Try
dr = cmd.ExecuteReader
While dr.Read()
lstOrder.Items.Add(dr("nummer") & " - " & dr("Omschrijving"))
End While
Catch
Debug.Print(sSQL1)
MsgBox("Error: " & sSQL1)
End Try
No idea if this works though (and for now I sadly can't test it).
Another question is: Do I need to use parameters for the dateadd (see query above) in the query as well? And if I do, how?
The last question is, when I am using the Parameters.Add, is it best to give a size value as well or is this not necessary?
Thank you in advance!
My answer to your first question that
I think this is the list of equal data-types you want:
SQL Server | OLEDB (ADO => ad+...)
-----------+---------------
char | Char
nchar | WChar
varchar | VarChar
nvarchar | VarWChar
text | LongVarChar
ntext | LongWVarChar

The SQL statement works properly in SQL Server database, but errors in vb.net

I need to insert new record into a SQL Server database, but get
Incorrect syntax error
The strange thing is when I try to query the same statement in SQL Server itself, it works properly.
The code in vb.net is as follows:
insertSql = "INSERT INTO Seg_LINE VALUES (" & OBJECTID & ", 'test" + "', '" + "test" + "','" + DrainName + "'," & UID & ")"
logger.Info("insert sql = " + insertSql)
Dim cmdInsert As New SqlClient.SqlCommand(insertSql, Sqlconnection)
cmdInsert.ExecuteNonQuery()
The OBJECTID and UID are number parameters.
I cannot figure out what's wrong with my code, I am using vb.net(vs2102).
Most likely you have a DrainName value with a single quote in it. You're lucky the query is just failing, and not executing unwanted commands on your DB server. Don't use string concatenation like that to build queries! You need to use query parameters, like this:
insertSql = "INSERT INTO Seg_LINE VALUES (#ObjectID, 'test', 'test', #DrainName, #UID)"
logger.Info("insert sql = " + insertSql)
Dim cmdInsert As New SqlClient.SqlCommand(insertSql, Sqlconnection)
'I'm guessing at these parameter types. Use the actual db types of the columns
cmdInsert.Parameters.Add("#ObjectID", SqlDbType.Int).Value = OBJECTID
cmdInsert.Parameters.Add("#DrainName", SqlDbType.NChar, 50).Value = DrainName
cmdInsert.Parameters.Add("#UID", SqlDbType.Int).Value = UID
cmdInsert.ExecuteNonQuery()
Changing the code this way will also likely fix your syntax error.

How to update MS Access Database (vb.net)

I am created a journal program for an internship project and I am using a MS-Access Database. I am programming in VB.net. Now, I am trying to make it so that they can "Update" their journals, meaning that they click on their calendar date and it brings them to that journal if they have one for that date. If they have one for that date then it shows the title and journal text entry for that date. I want to make it so that any changes they have made to the journal (editing the textbox fields) are also changed in the database when they click the update button. Here's what i have so far
Private Sub COE_JournalBtn_Click(sender As System.Object, e As System.EventArgs) Handles COE_JournalBtn.Click
If DateTimePicker1.Value <> Nothing Then
If TitleTxt.Text <> "" Then
If JournalTextRtxt.Text <> "" Then
myConnection.Open()
Dim DatePicked As String = DateTimePicker1.Value
Dim cmd As OleDbCommand
Dim str As String
Try
MyJournalTitle = TitleTxt.Text
MyJournalText = JournalTextRtxt.Text
str = "UPDATE Journals SET JournalTitle='" & MyJournalTitle & "', JournalText='" & MyJournalText & "' WHERE JournalDate=" & DatePicked
cmd = New OleDbCommand(str, myConnection)
cmd.ExecuteNonQuery()
myConnection.Close()
Catch ex As Exception
MessageBox.Show("There was an error processing your request. Please try again." & vbCrLf & vbCrLf & _
"Original Error:" & vbCrLf & vbCrLf & ex.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
myConnection.Close()
End Try
myConnection.Close()
End If
End If
End If
End Sub
Now my update string by itself is
"UPDATE Journals SET JournalTitle='" & MyJournalTitle & "', JournalText='" & MyJournalText & "' WHERE JournalDate=" & DatePicked
Now, what happens, is absolutely nothing. No errorboxes come up. No messageboxes appear. The program doesn't freeze. And the database remains unchanged. What am I doing wrong? Is there an error in my code or something missing? Please help me because I really want to figure this out and i've been looking everywhere for a solution in VB.net and cannot find one that applies to me being that I am using MS-Access and NOT SQL.
Thanks in advance,
Richard Paulicelli
Use a parametrized query to avoid Sql Injection Attacks and quoting problems
str = "Journals SET JournalTitle=?, JournalText=? WHERE JournalDate=?"
cmd = New OleDbCommand(str, myConnection)
cmd.Parameters.AddWithValue("#jounalTitle", MyJournalTitle )
cmd.Parameters.AddWithValue("#journalText", MyJournalText)
cmd.Parameters.AddWithValue("#journalDate", DatePicked)
cmd.ExecuteNonQuery()
Using parameters will free your code from that continue quoting that expose your code to an high chance of typing errors. And you don't have any problem with Sql Injection
You may have a problem with this part of your UPDATE statement:
"' WHERE JournalDate=" & DatePicked
If the Journals field, JournalDate, is Date/Time data type, surround the date string value with Access date delimiter characters (#).
"' WHERE JournalDate=#" & DatePicked & "#"
You can also convert your date string to yyyy-mm-dd format to avoid misinterpreting the date literal based on local.
I agree with the suggestions to use a parameter query for this instead. I'm just trying to help you understand why the original attempt may have failed.

Resources