1

I'm having trouble with an SQL query. The problem is that I'm querying an external database of enterprise names and some names are like "Martha's" (include apostrophes). And because I'm querying from an android app, the query string looks like:

String query = "Select * from Advertiser where AdvName= '" + name + "';";

So is there anyway I could ignore or change the apostrophes in the query?

Thanks in advance!

TJ Thind
  • 784
  • 5
  • 17
Carlos Tirado
  • 297
  • 1
  • 5
  • 20

2 Answers2

6

That's one of the reasons why you should always use prepared statements when executing parameterized queries:

String sql = "select * from Advertiser where AdvName = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, name);
ResultSet rs = stmt.executeQuery();

The JDBC driver will escape the quotes for you, and this will also prevent SQL injection attacks.

Prepared statements also have performance advantages when you must execute the same query several times but with different parameters.

Read more about prepared statements in the JDBC tutorial.

Side note: you shouldn't have a ; at the end of your query.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

In PLSQL you should use double '' in the input-field, meaning, Martha's => Martha''s:

String query = "Select * from Advertiser where AdvName= 'Martha''s';";


Important Remark:
For security purposes (to avoid sql injection) you should avoid creating queries the way you do, better use prepared-statement and set the parameters like this:

String query = "Select * from Advertiser where AdvName= ? ";
PreparedStatement  st   = conn.prepareStatement(query);
st.setString(1,name);
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129