JNDI连接数据库(连接池)
public class DBConnection {
public PreparedStatement pstmt = null;
public Statement stmt = null;
public Connection con = null;
public ResultSet rs = null;
public Result r = null;
// JNDI获取数据源
public Connection getConnection() {
try {
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/books");
con = ds.getConnection();
} catch (NamingException e) {
e.printstacktrace();
} catch (sqlException e) {
e.printstacktrace();
}
return con;
}
// 通用查询方法
public Result executeQuery(Connection con,String sql,Object[] params)
throws sqlException {
pstmt = con.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
pstmt.setobject(i + 1,params[i]);
}
rs = pstmt.executeQuery();
r = ResultSupport.toResult(rs);
return r;
}
// 通用增删改方法
public int executeUpdate(Connection con,params[i]);
}
int num = pstmt.executeUpdate();
return num;
}
// 关闭数据资源 public void closeAll() { if (pstmt != null) { try { pstmt.close(); } catch (sqlException e) { e.printstacktrace(); } } if (stmt != null) { try { stmt.close(); } catch (sqlException e) { e.printstacktrace(); } } if (con != null) { try { con.close(); } catch (sqlException e) { e.printstacktrace(); } } if (rs != null) { try { rs.close(); } catch (sqlException e) { e.printstacktrace(); } } }}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。