标签:
1 package com.eden.utils; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 import java.sql.Statement; 8 9 import javax.ejb.Local; 10 import javax.sql.DataSource; 11 12 import com.mchange.v2.c3p0.ComboPooledDataSource; 13 14 public class JdbcUtils { 15 private static ThreadLocal<Connection> local = new ThreadLocal<Connection>(); 16 private static ComboPooledDataSource dataSource; 17 static{ 18 try { 19 dataSource = new ComboPooledDataSource("day13"); 20 } catch (Exception e) { 21 e.printStackTrace(); 22 } 23 } 24 public static DataSource getDataSource(){ 25 return dataSource; 26 } 27 public static Connection getConnection() throws SQLException{ 28 Connection conn = local.get(); 29 if(conn == null){ 30 conn = dataSource.getConnection(); 31 local.set(conn); 32 } 33 return conn; 34 } 35 36 37 public static void closeResource(Connection conn, Statement st, ResultSet rs){ 38 try { 39 if(rs != null){ 40 rs.close(); 41 } 42 } catch (SQLException e) { 43 e.printStackTrace(); 44 }finally{ 45 try { 46 if(st != null){ 47 st.close(); 48 } 49 } catch (SQLException e) { 50 // TODO Auto-generated catch block 51 e.printStackTrace(); 52 }finally{ 53 try { 54 if(conn != null){ 55 conn.close(); 56 } 57 } catch (SQLException e) { 58 // TODO Auto-generated catch block 59 e.printStackTrace(); 60 } 61 } 62 } 63 } 64 public static void commitAndClose(Connection conn){ 65 try { 66 if(conn != null){ 67 conn.commit(); 68 } 69 } catch (SQLException e) { 70 e.printStackTrace(); 71 }finally{ 72 JdbcUtils.closeResource(conn, null, null); 73 } 74 } 75 public static void rollbackAndClose(Connection conn){ 76 try { 77 if(conn != null){ 78 conn.rollback(); 79 } 80 } catch (SQLException e) { 81 e.printStackTrace(); 82 }finally{ 83 JdbcUtils.closeResource(conn, null, null); 84 } 85 } 86 }
标签:
原文地址:http://www.cnblogs.com/IronPillar/p/5701972.html