java—c3p0utils封裝


封裝C3P0簡化代碼量

public class C3P0utils {
    private static ComboPooledDataSource dataSource = new ComboPooledDataSource();

    public static DataSource getDataSource(){
        return dataSource;
    }
    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

測試類

public class Test_c3p0util {
    @Test
    public void test2() {
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            // 1.獲取連接
            conn = C3P0utils.getConnection();
            // 2.編寫sql語句
            String sql = "insert t1 (id,name) value (?,?)";
            // 3.獲取執行sql語句對象
            pstmt = conn.prepareStatement(sql);
            // 4.設置參數
            pstmt.setInt(1, 7);
            pstmt.setString(2, "wuwuww");
            // 5.執行刪除操作
            int row = pstmt.executeUpdate();
            if (row > 0) {
                System.out.println("刪除成功!");
            } else {
                System.out.println("刪除失敗!");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 6.釋放資源
            JBDC_V2.release(conn, pstmt, null);
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM