Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying a variable name in QUERY WHERE clause in JDBC

Tags:

java

mysql

jdbc

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

like image 775
Noona Avatar asked Apr 09 '10 14:04

Noona


People also ask

How do you set a variable in SQL query?

Setting a Value in a Transact-SQL Variable To assign a value to a variable, use the SET statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement.

Which method is used to perform SELECT query in JDBC?

1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the object of ResultSet. 2) public int executeUpdate(String sql): is used to execute specified query, it may be create, drop, insert, update, delete etc.


3 Answers

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();
like image 192
Peter Lang Avatar answered Oct 28 '22 23:10

Peter Lang


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

like image 42
CoolBeans Avatar answered Oct 29 '22 00:10

CoolBeans


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.

like image 31
BalusC Avatar answered Oct 28 '22 23:10

BalusC