tags:

views:

686

answers:

7

I have a database with names in it such as John Doe etc. Unfortunately some of these names contain quotes like Keiran O'Keefe. Now when I try and search for such names as follows: SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe' I (understandably) get an error.

How do I prevent this error from occurring. I am using Oracle and PLSQL.

A: 

Found in under 30s on Google...

Oracle SQL FAQ

Rob Cooper
A: 

Input filtering is usually done on the language level rather than database layers.
php and .NET both have their respective libraries for escaping sql statements. Check your language, see waht's available.
If your data are trustable, then you can just do a string replace to add another ' infront of the ' to escape it. Usually that is enough if there isn't any risks that the input is malicious.

paan
A: 

I suppose a good question is what language are you using?
In PHP you would do: SELECT * FROM PEOPLE WHERE SURNAME='mysql_escape_string(O'Keefe)'
But since you didn't specify the language I will suggest that you look into a escape string function mysql or otherwise in your language.

Unkwntech
+14  A: 
Matt Sheppard
+1 for recommending bind variables. If you use bind variables annoying things like this don't ever happen, and your queries are better, and you aren't open to SQL injection attacks.
Chris Gill
+1  A: 

Parameterized queries are your friend, as suggested by Matt.

Command = SELECT * FROM PEOPLE WHERE SURNAME=?

They will protect you from headaches involved with

  • Strings with quotes
  • Querying using dates
  • SQL Injection
Conrad
+1  A: 

Use of parameterized SQL has other benefits, it reduces CPU overhead (as well as other resources) in Oracle by reducing the amount of work Oracle requires in order to parse the statement. If you do not use parameters (we call them bind variables in Oracle) then "select * from foo where bar='cat'" and "select * from foo where bar='dog'" are treated as separate statements, where as "select * from foo where bar=:b1" is the same statement, meaning things like syntax, validity of objects that are referenced etc...do not need to be checked again. There are occasional problems that arise when using bind variables which usually manifests itself in not getting the most efficient SQL execution plan but there are workarounds for this and these problems really depend on the predicates you are using, indexing and data skew.

Ethan Post
+1  A: 

Oracle 10 solution is

SELECT * FROM PEOPLE WHERE SURNAME=q'{O'Keefe}'
Laurent Schneider