StrataFrame Forum

Single quotes in a string cause errors

http://forum.strataframe.net/Topic2016.aspx

By Andria Jensen - 7/31/2006

I have some string fields on a few of my forms that have apostrophes (single quotes) in them in the database.  Things like New Year's Day cause errors when I go to save the BO using the Save method.  How do I get around this?
By StrataFrame Team - 7/31/2006

What is the error message you're receiving?  All of the saves are parameterized, so having apostrophes within your values shouldn't matter.  We use apostrophes and special characters in our field values all the time.  If you can post the exception and any inner exceptions (or just the output from the red error window), that should be enough.
By Andria Jensen - 7/31/2006

I get "An error occurred while saving data to the server" when I try to save.

I also sometimes get:
Line 1: Incorrect syntax near 's'.
Unclosed quotation mark before the character string ''.

By StrataFrame Team - 7/31/2006

When you run your application, in your SetDataSources() method of the AppMain.vb file, after the call to ConnectionManager.SetConnections(), add this line:

MicroFour.StrataFrame.DataLayer.DataSources("").SetDebugOn("C:\SFDebug.html", True)

When you run your app, and try to save, it will record the debug results to that output file.  Then, if you can attatch the file to a forum post, it will tell me the syntax of the command that it's trying to execute and should help me figure out what's going on.  Thanks.

By Andria Jensen - 7/31/2006

Sorry about this one...I think it's my mistake in a SQL statement I didn't realize it was hitting.
By StrataFrame Team - 7/31/2006

Hehe, that's not a problem.  If you have any problems on the save, just post that debug output along with the post, and it will help us solve the problem much faster.

If you ever need to send values to the server (especially string values, since they can contain single quotes), don't concatenate a bunch of strings together into the whole command; parameterize the command instead.  Parameterizing commands also helps SQL Server to cache the execution path of the command for future executions since the command text itself doesn't change, just the values of the parameters.

So, instead of this:

Me.FillDataTable("SELECT * FROM MyTable WHERE MyField = '" & SomeValue & "'")

Do this:

Dim loCommand As New SqlCommand()
loCommand.CommandText = "SELECT * FROM MyTable WHERE MyField = @MyValue"
loCommand.Parameters.Add("@MyValue", SqlDbType.NVarChar)
loCommand.Parameters("@MyValue").Value = MyValue
Me.FillDataTable(loCommand)

You'll notice that you can pass a DbCommand object to the data source for execution (which is your SqlCommand object).  Have fun Smile