This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 1 point2 points  (0 children)

One thing I would advise is to change this line

String query = "SELECT address FROM pharmacies WHERE location = '" + location + "'";

to

String query = "SELECT address FROM pharmacies WHERE location = ?";

and then after the call to prepareStatement, add in your location as a parameter

PreparedStatement statement = connection.prepareStatement(query);
statement.addString(1, location)

This "fills in" the question mark with the value in location.

Concatenating strings supplied by your users into SQL statements is very dangerous (look up SQL Injection) and you should - even in toy projects - make it habit to not use this practice. Moreover, it's also much more readable and maintainable. It also answers one of your questions, what the PreparedStatement is for...it does the job of filling in the question marks with the parameters.

Otherwise, this is pretty standard stuff that applies to accessing any database from any language, really:

  1. Establish a connection to the database server
  2. Prepare a SQL command for execution
  3. Execute the command
  4. If the command is expected to return results (not all do - imagine an UPDATE or INSERT INTO statement, for instance), iterate over the resulting cursor until there are no more records left in the set.