利用回調(diào)簡化JDBC編程
簡單看了一下spring 的jdbc支持,現(xiàn)在又要直接用到jdbc,想想就是痛苦。于是參考了spring,自己寫了一些簡單的java封裝類來簡化編程。
廢話少說,我這里就用代碼來代言吧,看看怎樣簡化我們的JDBC編程,可以和以前進行對比。
(1) JdbcTemplate。
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;import javax.sql.DataSource;import org.winter.util.DBUtil;/**
?* a simple JDBC template 模仿spring的JdbcTemplate
?*
?* @author bluestone
?* @version 1.0 2006-8-8
?*
?*/
public class JdbcTemplate {?private DataSource dataSource = null;?public JdbcTemplate(DataSource ds) {
??this.dataSource = ds;
?}/**
? * 執(zhí)行更新操作
? *
? * @param sql
? * @param setter
? * @return
? * @throws SQLException
? */
?public int update(String sql, PreparedStatementSetter setter)
???throws SQLException {
??Connection conn = null;
??reparedStatement ps = null;
??try {
???conn = dataSource.getConnection();
???ps = conn.prepareStatement(sql);
???setter.setValues(ps);
???return ps.executeUpdate();
??} finally {
???DBUtil.colseConnection(conn, ps, null);
??}
?}?/**
? *
? * @param sql
? * @return
? * @throws SQLException
? */
?public boolean execute(String sql) throws SQLException {
??Connection conn = null;
??Statement stmt = null;
??try {
???conn = dataSource.getConnection();
???stmt = conn.createStatement();
???return stmt.execute(sql);
??} finally {
???DBUtil.colseConnection(conn, stmt, null);
??}
?}?/**
? *
? * @param sql
? * @param setter
? * @param extractor
? * @return
? * @throws SQLException
? */
?public Object query(String sql, PreparedStatementSetter setter,
???ResultSetExtractor extractor) throws SQLException {
??Connection conn = null;
??reparedStatement ps = null;
??ResultSet rs = null;
??try {
???conn = dataSource.getConnection();
???ps = conn.prepareStatement(sql);
???setter.setValues(ps);
???rs = ps.executeQuery();
???return extractor.extractData(rs);
??} finally {
???DBUtil.colseConnection(conn, ps, rs);
??}
?}?// .........................
}(2)? PreparedStatementSetterpublic interface PreparedStatementSetter {
?void setValues(PreparedStatement ps) throws SQLException;
}(3)?
ResultSetExtractorpublic interface ResultSetExtractor {
?Object extractData(ResultSet rs) throws SQLException;
}(4) 可以參考spring自己定義其他接口。。。
用了這些輔助類,我們就可以像用spring那樣編程了(當然這只能用在對事務要求不高的應用環(huán)境中)。看看怎么使用:
?
private JdbcTemplate template;?public JobManageDao() throws BusinessException {
??try {
???template = new JdbcTemplate(DBHelper.getDataSource());
??} catch (NamingException e) {
???throw new BusinessException(e);
??}
?}public long saveJobInfo(final JobInfo info) throws BusinessException {
??final long id = IdGenerator.getIdLong();
??try {
???int j = template.update(INSERT_JOB_SQL, new PreparedStatementSetter() {??public void setValues(PreparedStatement ps) throws SQLException {
?????int i = 1;
?????ps.setLong(i++, id);?? //......???}
???});
????? return j > 0 ? id : 0L;
??} catch (SQLException e) {
???? ?throw new BusinessException(e);
??}
?}