views:

142

answers:

3

Could someone please give me a link on how to create a query in JDBC that gets a variable name in the WHERE statement, or write an example, to be more specific, my code looks something like this:

      private String getLastModified(String url) {
     String lastModified = null;
     ResultSet resultSet;
String query = "select LastModified from CacheTable where " + 
     " URL.equals(url)";
     try {
      resultSet = sqlStatement.executeQuery(query);
}

Now I need the syntax that enables me to return a ResultSet object where URL in the cacheTable equals url from the method's argument.

thanks

+2  A: 

The easiest way would be

String query = "select LastModified from CacheTable where url = '" + url +"'";

You should use bind variables though:

String query = "select LastModified from CacheTable where url = ?";
prepStmt = conn.prepareStatement(query);
prepStmt.setString(1, url);
rs = prepStmt.executeQuery();
Peter Lang
Thanks for your answer, what are the other ways, and how do I bind variables?
Noona
oh.. I thought prepareStatement was just for update queries. thank you very much
Noona
+1 I was far too slow. More coffee!
Instantsoup
I have another question, how do I execute the query, in particular, how do i get the ResultSet object ?(you can ignore it, i noticed the edit now, thanks)
Noona
A: 

To take it one step further you should really use DBUtils from apache-commons or Sping JDBC framework. A lot of JDBC work is mundane and error prone due to the number of steps involved with it. Both links have working examples for you to get started.

These helper libraries will make your life much more comfortable :-).

CoolBeans
A: 

To clear a misconception: JDBC and SQL are two entirely different things. Databases only understand the SQL language. It's a (semi)standard which you can learn here. JDBC is just a Java API which enables you to execute SQL language using Java code. Nothing less, nothing more. JDBC is not a Java way of writing SQL language or so. It's just the messenger between Java code and the database. You can learn JDBC here.

That said, yes, the PreparedStatement is the way to go to set values in a SQL query. It not only eases setting fullworthy Java objects in a SQL string using the setXXX() methods, but it also saves you from SQL injection attacks.

BalusC