Properly encoding a SQL statement through a Function

Contributed by
Rating: 3 stars3 stars3 stars3 stars3 stars / 6
October 15, 1999
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

One of the biggest questions that people come to me regarding SQL statements is when the data that they need to store in the database contains a single quote (my dog's name is scoobie). Normally, if you were to do a simple select statement on a database it would give you an error. This is because in most popular databases the single quote is used as a text delimiter. That is, it is used to mark the start and end of a string.



SELECT * FROM authors WHERE fname = 'nothing'

Above, the value "rob" is delimited by the single quotes. Now if we attempted:

SELECT * FROM authors WHERE comments = 'my dog's name is scoobie'

You can see the obvious mistake. - comments = 'my dog'

The rest of the string will generate an error.

SOLUTION:
The solution is simple. What we need to do is double up the single qutoes. So, from our example above,

SELECT * FROM authors WHERE comments = 'my dog's name is scoobie'

Now becomes
SELECT * FROM authors WHERE comments = 'my dog''s name is scoobie'

The replace function will enable us to do this very easily.

The easiest way to solve this problem is to include a simple function in our utilities.inc file:


Function sqlEncode(sqlValue)
     sqlEncode = replace(sqlValue, "'", "''")
End function

Now whenever we build any sql statements all we need to do is use the sqlEncode function to encode our data.

sql = "SELECT * from FROM WHERE comments = '" & sqlEncode(strComments) & "'"


Author:
Robert Chartier
nothingmn@netexecutive.com
October 2, 1999
blog comments powered by Disqus
DATABASE CODE ARTICLES

- Deployment of the MobiLink Synchronization M...
- MobiLink Synchronization Wizard in SQL Anywh...
- Finding Matching Records in Data Access Pages
- Using the AccessDataSource Control in VS 2005
- A Closer Look at ADO.NET: The Command Object
- A Closer Look at ADO.NET: The Connection Obj...
- Using ADO to Communicate with the Database, ...
- Code Snippets: Counting Records
- Constraints In Microsoft SQL Server 2000
- Multilingual entries into a DB and to be dis...
- Two combos, one textbox example
- ADO Recordset Paging
- SQL Server Database Creator - .NET Version
- Getting A List of Tables From SQL Server
- Discussion & Listserv Module by Mike Eck...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 5 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials