千万可不敢乱搬代码哦

数据库连接池

利用单例模式,创建数据库连接池

public class DBUtils {
     

    private static String URL = "jdbc:mysql://127.0.0.1:3306/onlinemusic?useSSL=false";
    private static String USERNAME = "root";
    private static String PASSWORD = "root";

    private static volatile DataSource DATSSOURCE;

    private static DataSource getDataSource() {
     
        if (DATSSOURCE == null) {
     
            synchronized (DBUtils.class) {
     
                DATSSOURCE = new MysqlDataSource();
                ((MysqlDataSource) DATSSOURCE).setUrl(URL);
                ((MysqlDataSource) DATSSOURCE).setUser(USERNAME);
                ((MysqlDataSource) DATSSOURCE).setPassword(PASSWORD);
            }
        }
        return DATSSOURCE;
    }

    public static Connection getConnection() {
     
        try {
     
            Connection connection = getDataSource().getConnection();
            return connection;
        } catch (SQLException throwables) {
     
            throwables.printStackTrace();
            throw new RuntimeException("数据库连接失败!");
        }
    }

    public static void getClose(Connection connection, PreparedStatement statement, ResultSet resultSet) {
     
        if (resultSet != null) {
     
            try {
     
                resultSet.close();
            } catch (SQLException throwables) {
     
                throwables.printStackTrace();
            }
        }

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

        if (connection != null) {
     
            try {
     
                connection.close();
            } catch (SQLException throwables) {
     
                throwables.printStackTrace();
            }
        }
    }

你可能感兴趣的:(笔记,数据库,mysql,sql,单例模式,java)