开发者

Specifying a variable name in QUERY WHERE clause in JDBC

开发者 https://www.devze.com 2022-12-26 12:51 出处:网络
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:

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 getLastMo开发者_运维技巧dified(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


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();


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 :-).


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消