C 3 P 0データソースの使用

3027 ワード

c 3 p 0をJDBCUtilsクラスにカプセル化します.データベースの接続と使用を管理します.
public class JDBCTools {
    
    //        
    //    
    public static void commit(Connection connection){
        if(connection != null){
            try {
                connection.commit();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    //    
    public static void rollback(Connection connection){
        if(connection != null){
            try {
                connection.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    //    
    public static void beginTx(Connection connection){
        if(connection != null){
            try {
                connection.setAutoCommit(false);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    private static DataSource dataSource = null;

    //              . 
    static{
        dataSource = new ComboPooledDataSource("c3p0");
    }
    
    public static Connection getConnection() throws Exception {
        return dataSource.getConnection();
    }

    public static void releaseDB(ResultSet resultSet, Statement statement,
            Connection connection) {

        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection != null) {
            try {
                //        Connection      close  
                //         ,                     . 
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

c3p0-config.xml



    
        
        
        root
        1230
        com.mysql.jdbc.Driver
        jdbc:mysql:///atguigu
        
        
        5
        
        5
        
        5
        
        10

        
        20
        
        5