views:

286

answers:

3

I saw this example somewhere:

 rs = connection.prepareStatement("select * from table").executeQuery();

Could I use this format, if I want to execute a query like this "Select * from table where column = "hello" "?

The way in which I usual I use prepareStatement object is something like this:

        String sql = "select * from adresa where column = ?";
        PreparedStatement pre = con.prepareStatement(sql);
        pre.setString(1, i);
        rs = pre.executeQuery();

Later Edit:

I don't understand. Pascal Thivent wrote that I can use the short version with In parameters, but Liu tells me this is not possible. :) Anw, using Pascal's version, i receive this error: void cannot be dereferenced

A: 

of course u can use a string variable for the query in which u put in ur dynamic data and run it.

rs = connection.prepareStatement(variable).executeQuery();

Sabeen Malik
also if u want to do the dynamic replacing urself why not use 'statement' and executeUpdate()
Sabeen Malik
statement has different performance characteristics than prepared statement.
Ken Liu
@ken .. yes i always forget that one .. thank you for pointing that out :)
Sabeen Malik
A: 

You can only use the first form if there are no bind variables (question marks) in the query. It's just a shortened version of what you posted.

Also, if you use the shortened form you won't have the opportunity to reuse the PreparedStatement object.

Ken Liu
I don't understand. Pascal Thivent wrote that I can use the short version with In parameters, but you tell me this is not possible. :)Anw, using Pascal's version, i receive this error: void cannot be dereferenced
cc
A: 

The long form is often, but prepared statements can be precompiled by the db, and if used properly will help prevent sql injection.

Connection conn = null;
ResultSet rs = null;
PreparedStatement ps = null;
try {
 conn = getConn();
 ps = conn.prepareStatement("select * from x where y = ? "); //note no sb.append()'s or +'s, to helps prevent sql injection
 ps.setLong(1, 12l);
 rs = ps.executeQuery();

 while (rs.next()) {
 ... act ...
 }
} catch ( Exception e) {
} finally {
 if (rs != null) rs.close(); 
 if (ps != null) ps.close();
 if (conn != null) conn.close();
}

Who said java was verbose. :)

Nathan Feger