Thursday, March 29, 2012

single quotes are messing me up please help

Hi, Im doing a simple update into a long text field of a sql server database from an .aspx page.

Here is my code:

Dim MyCommand As String = "UPDATE tblPropOL SET fldDesc = '" & CStr(frmText.Text) & "' where pr_idno = " & CInt(lblID2.Text) & ""
Dim comm As New SqlCommand(MyCommand, MyConnection)
MyConnection.Open()
comm.ExecuteNonQuery()

This works great for most records in the database, but, if there is a single quote in the text field I am trying to update, I get an error because i guess it thinks the single quote is supposed to do something in my code.

What can I do to get around this?

here is the error:

Line 2: Incorrect syntax near 's'. Unclosed quotation mark before the character string ' where pr_idno = 1115'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Line 2: Incorrect syntax near 's'. Unclosed quotation mark before the character string ' where pr_idno = 1115'.

Obviously this is a long text field, so I want some words to have apostrophes...any work arounds? thanks.

-JBDYeah, you have to double up the single quotes. Do a replace on the string and replace each single quote with two. Then remember to reverse the procedure when you read the strings back out.

Don
Take a look at this tutorial:
http://aspnet101.com/aspnet101/tutorials.aspx?id=2

however, the best way to handle this is with parameterized queries - - that way, you don't need to worry about the quotes around the data:
http://aspnet101.com/aspnet101/tutorials.aspx?id=1
Augustwind, thanks, you are exactly right. I paramerterized the query and it works like a charm. Much easier then the replace thing. thanks.

-JBD

0 comments:

Post a Comment