• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Queries with string parameters

 
Jason Kwok
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've got what I hope to be a small obstacle here. I'm trying to get my servlet to run a query that will search by an author's name, which in my database is a string.

Author is read in from the URL using the following:
String author = request.getParameter("author");

Here is my current query:
String query = "SELECT * FROM book WHERE active = 1 AND author = '" + author + "'";

which is sent to my database as:
SELECT * FROM book WHERE active = 1 AND author = 'John Doe'

Using this gives me an SQLException. What am I doing wrong?
 
Craig Jackson
Ranch Hand
Posts: 405
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you post the complete stack trace? It might be helpful.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 35279
384
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jason,
Have you tried running the SQL statement at the command line? This will help narrow down the problem and may give you a clearer error message.

You should also consider using a prepared statement.
SELECT * FROM book WHERE active = 1 AND author = ?

This protects you from the user entering "Jason's Text" as an author name, which would break the query.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic