import java.sql.*;import java.util.*;publicclass DbWrapper
{// 定义连接池对象为静态变量,将一直存在,直到工作目录关闭。privatestatic DataSource ds =null; // 1.用连接池的方式获得连接// 如果不是做多数据库程序,推荐使用此方法// 相关内容:在tomcat管理界面配置连接池publicstatic Connection openConnection()throws Exception
{// 只需要初始化1次if( ds ==null){
Context initContext =newInitialContext();
Context envContext =(Context) initContext.lookup("java:/comp/env");
DataSource ds =(DataSource) envContext.lookup("jdbc/MyDataSource");}return ds.getConnection();}// 2.用jdbc驱动获得连接// 相关内容:JSP数据库连接大全publicstatic Connection openConnection(
String driver,
String url,
String username,
String password)throws Exception
{
Class.forName(driver).newInstance();return DriverManager.getConnection(url, username, password);}publicstaticvoidcloseConnection(Connection conn)throws Exception
{if( conn !=null){
conn.close();}} publicstaticintexecuteUpdate(String sql)throws Exception
{int count =0;
Connection conn =null;
Statement stmt =null;try{
conn =openConnection();
stmt = conn.createStatement();
count = stmt.executeUpdate(sql);}catch( Exception e ){throw e;}finally{closeConnection(conn);}return count;}publicstatic List executeQuery(String sql)throws Exception
{
List list =newArrayList();
Connection conn =null;
Statement stmt =null;
ResultSet rs =null;try{
conn =openConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();while( rs.next()){
Map map =newHashMap();for(int i =1; i <= rsmd.getColumnCount(); i++){
map.put(rsmd.getColumnName(i), rs.getObject(i));}
list.add(map);} }catch( Exception e ){
e.printStackTrace();}finally{if( rs !=null) rs.close();closeConnection(conn);}return list; }}
|