Bitten by Escaping Single Quotes
August 17, 2007 at 11:55 AM
—
mgordon
I've known about it and handled it well for years. You know...when you have a string with a single quote embedded in it and you need to insert the string into a database column. For the longest time, I simply replaced any quotes with two quotes and all was well. ADO.Net was smarter than I gave it credit for, however, and it apparently hung me up.
I've been working on a brand new client-server application for the past several months. I created the dal that was to be used by the entire application and it had been working well. We just started allowing some user acceptance testing and it happened. A user keyed in a string with an apostrophe in it and the application thre an exception. "No problem", I thought, "I'll just replace any quotes with two quotes and I'm on my way".
One of the developers on this project approached me, shortly after, and pointed out that quotes I was doubling in the dal were, in fact, being saved in the database as double quotes. Huh? After two hours of debugging and tweaking I figured out the problem. I found a post on Scott Gutherie's blog that pointed out that the SqlParameter class automatically takes care of escaping single quotes. So why was it seemingly ignoring my quotes?
Turns out that the problem laid with the creation of the actual parameters. I had created an interface and my Dal class implemented it. Besides the other benefits to ding this, I wanted to be able to write specific implementations for different databases and be able to switch them out, if needed, without changing any of the application code. So, necessarily, all the application code was written against the interface and not the specific dal class. A side effect of this was that the code that called into the dal could not create specific parameter clases such as SqlParameter, but rather it asked the dal to create a parameter specific to the database the class was written for, and the parameter was stored in a variable of type IDataParameter.
Long story short, the dal contained a method called CreateParameter that looked like this
Public Function CreateParameter(ByVal name As String, ByVal value As Object) As IDataParameter
Implements IDAL.CreateParameter
Return New SqlParameter(name, value)
End Function 'CreateParameter
Note that this method does not specify a DBType for the parameter. Apparently, the lack of a type confused the SqlParameter class. I modified the dal to check each parameter being passed in to see if it was a string type. If it was, I manually set it to a DBType of Varchar. This worked, in my case, because our standard was to use varchars for all string data types unless a char made more sense. At any rate, this modification allowed me to remove the code that manually escaped the single quote. The SqlParameter class now had all it needed to handle the situation on its own.