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; }} |