I have the following code to executing a sql query:
query = String.format("select * from users where user_name = '%s';", results.getString(1));
results2 = mStmt.executeQuery(query);
One user_name in the dataset has value “O’brien”. This ruins my query due to the single parenthesis in “O’brien. The query would become:
select * from users where user_name = 'O'brien'
What is the strategy to overcome this and not modify the data?
EDIT: The prepared statement does fix the single quote problem however that was only part of the problem. One of the string values I have contains the word “UNDER”. which is a SQL keyword. For example I have a preparedStatement called insertAll with the query:
insert into names (id, val1, val2, val3, val4, tTime, val5) values (?, ?, ?, ?, ?, ?, ?)
Thanks for all the help!
Set your parameters with prepareStatement. Your code is a SQL injection exploitable code from the book.
http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html