Re: jdbc query
- From: Thomas Hawtin <usenet@xxxxxxxxxxxxxxxxx>
- Date: Tue, 04 Jul 2006 19:58:36 +0100
2rajesh.b@xxxxxxxxx wrote:
i am working using jdbc prepared statement in our application the below
is the sample code ,i am able to print the query using logger but the
resultset is not getting executed.
> if (etf == null) {
> etf = new EmployerTeamForm();
> }
It's best to check arguments, rather than try to do something random instead.
Does the ResultSet.toString cause the results to be iterated through. ResultSet.first might move the cursor back to the first result.
StringBuffer sb = new StringBuffer();
sb.append("SELECT ");
There is no point in using StringBuffer here. Literal strings will get concatenated at compile time (use javap -c on the class to see what happens).
}
catch (Exception ex) {
throw new ServiceException(this, ex);
It's generally best to catch specific exceptions.
}
finally {
try {
if (rs != null)
rs.close();
if (ps != null)
ps.close();
if (conn != null)
conn.close();
If rs.close throws an exception, ps and conn will not be closed.
The general form of resource handling is: acquire try { use } finally { release }. So:
ResultSet results = statement.executeQuery();
try {
... use results ...
} finally {
results.close();
}
Only needs a single catch, no null testing and it works.
You can use the execute around idiom to tidy this lot up:
public EmployerTeamForm load(
final EmployerTeam employerTeam
) throws ServiceException {
if (employerTeam == null) {
throw new NullPointerException();
}
return new ExecuteQuery<EmployerTeamForm>() {
protected void init(
PreparedStatement statement
) throws SQLException {
statement.setInt(1, employerTean.getCompanyID());
statement.setInt(2, employerTean.getUserID());
}
protected EmployerTeamForm handle(
ResultSet results
) throws SQLException {
if (!results.next()) {
return null;
}
...
return form;
}
}.executeQuery(
connection,
"..."
);
}
With the non-query specific:
public class ExecuteQuery<T> {
protected abstract void init(
PreparedStatement statement
) throws SQLException;
protected abstract T handle(
ResultSet results
) throws SQLException;
public final T executeQuery(
Connection connection, String sql
) throws ServiceException {
try {
PreparedStatement statement =
connection.prepareStatement(sql);
try {
init(statement);
ResultSet results = statement.executeQuery();
try {
handle(results);
} finally {
results.close();
}
} finally {
statement.close();
}
} catch (SQLException exc) {
throw new ServiceException(exc);
}
}
}
(Disclaimer: Not compiled or tested.)
Tom Hawtin
--
Unemployed English Java programmer
http://jroller.com/page/tackline/
.
- References:
- jdbc query
- From: 2rajesh . b
- jdbc query
- Prev by Date: Re: jdbc query
- Next by Date: Connect:Direct & Java?
- Previous by thread: Re: jdbc query
- Next by thread: Re: What is CRUD?
- Index(es):
Relevant Pages
|