DBUtils.java

    1. import com.mchange.v2.c3p0.ComboPooledDataSource;
    2. import javax.sql.DataSource;
    3. import java.sql.Connection;
    4. import java.sql.SQLException;
    5. /**
    6. * Function:
    7. * Time: 2022/2/8 13:44
    8. */
    9. public class DBCUtils {
    10. private static DataSource ds;
    11. static {
    12. ds = new ComboPooledDataSource();
    13. }
    14. public static DataSource getDataSource() {
    15. return ds;
    16. }
    17. public static Connection getConnection() throws SQLException {
    18. return ds.getConnection();
    19. }
    20. public static void closeConnection(Connection conn){
    21. try {
    22. if(conn!=null && !conn.isClosed()){
    23. conn.close();
    24. }
    25. } catch (SQLException e) {
    26. e.printStackTrace();
    27. }
    28. }
    29. }

    DBUtils的使用需要导包,并且需要依赖c3p0或者是druid来提供数据源。