tags:

views:

101

answers:

5

Hello.

I am trying to write an sql query and I am having a problem. When we want to write a query with a where clause to narrow down our results, we can do

... where name = 'John'

(Where name is a column in the table). Now I am trying to insert a clause like this except the name is "O'Malley". So I thought the query would be

... where name = 'O'Malley'

but this gives me a null pointer exception. Does anyone know how you could solve this problem?

Thanks for your help in advance.

+1  A: 

Depending on the database you could escape the ' I think. Have a look at http://dev.mysql.com/doc/refman/5.0/en/string-syntax.html

imnotneo
+3  A: 

Your problem is that the single quote in the string "O'Malley" is interpreted by SQL as the string terminator. To escape a single quote, replace it with two single quotes, like this:

where name = 'O''Malley'

Edit: If the string "O'Malley" came from a user input, your code is vulnerable to an SQL injection exploit. To avoid this risk, use a parameterized query.

Martin B
@Richbits... it does produce "O'Malley" you know, single quote and all
Iain Hoult
Yes, sorry my misinformation has been removed.
Richbits
+1  A: 

If you use two apostrophes together in you search string SQL will realise that it is part of the string and isn't part of the SQL syntax.

where name = 'O''Malley'
Iain Hoult
+1  A: 

Thanks Iain and Martin. Your soloution worked fine for me. Thanks again.

where name = 'O''Malley'

+2  A: 

Use bind variables to avoid thinking about quotation problems. Bind variables beware of sql injection to.

Christian13467
-1 for being vague to the original poster
esabine