I am trying to make some small changes to an old VB web app I need to add quotes inside of a string I've had no luck so far. The string is
Dim sql As String = "Select * from Usertask Where UserId = " & Session("UserId") & " and JobID=" & ddlReqTask.SelectedValue
I need to add quotes around the Session("UserID") value.
To escape a single or double quote in a string, use a backslash \ character before each single or double quote in the contents of the string, e.g. 'that\'s it' .
To print quotes, using escape characters we have two options: For single quotes: \' (backslash followed by single quote) For double quotes: \” (backslash followed by double quotes)
No escaping is used with single quotes. Use a double backslash as the escape character for backslash.
You can use ""
to insert a quote into a string e.g:
dim sometext as String = "Hello ""Frank"" how are you?"
Which gives you
Hello "Frank" how are you?
To escape a quote you just need to add another quote, I believe this is what you need:
Dim sql As String = "Select * from Usertask Where UserId = """ & Session("UserId") & """ and JobID=" & ddlReqTask.SelectedValue
This is a SQL injection vulnerability and you should NOT be doing it. By doing it this way, you allow your users to execute any query they want to by giving you a UserId like
'; DROP TABLE Usertask; --
Instead, use parameters. Depending on how you are executing the SQL, there are different ways to do it; please show us the code that executes the SQL query.
In answer to your question,
Dim StringWithQuotes As String = "Hello, I've got ""Quotes""!"
This string will be
Hello, I've got "Quotes"!
I'd recommend you use parameterised SQL instead of building up an adhoc SQL statement like this as you could leave yourself open to SQL injection. This means you don't need to worry about concatenating quotes into the string, as well as also improving query performance (assuming sql server) as it allows execution plan caching and reuse.
e.g.
Dim sql As String = "Select * from Usertask Where UserId = ? AND JobID = ?"
Then add 2 ADODB.Parameters to the Command object to supply the values for the 2 parameters e.g.
Set param = New ADODB.Parameter
param.Name = "@UserId"
param.Direction = adParamInput
param.Type = adVarChar
param.Size = (give size of user id field)
param.value = Session("UserId")
yourADOCommand.Parameters.Append param
And the same again for the JobId parameter.
You could also use Chr(34)
in the concatentation.
Dim sql As String = "Select * from Usertask Where UserId = " & Chr(34) & Replace(Session("UserId"), Chr(34), Chr(34) & Chr(34)) & Chr(34) & " and JobID=" & CLng(ddlReqTask.SelectedValue)
Either way works (the other examples and this one). some people prefer this one as it can be less confusing, however the above examples arent perfectly ledgible and arent exatly rocket science
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With