【问题标题】:How to update ArrayList only when it's added data in MySQL?如何仅在 MySQL 中添加数据时更新 ArrayList?
【发布时间】:2020-07-14 12:19:54
【问题描述】:

我正在做书店,我有一个“购物车”按钮,可以打开购物车,用户可以看到他添加的所有内容。问题是每次单击该按钮时,我都会执行选择查询并将该书添加到 ArrayList 中。例如,用户在购物车中添加了 2 本书,所以每次我单击“购物车”按钮时,它都会将这两本书添加到 ArrayList 中并显示它们(数据库中的一切都很好)。这就是方法的样子:

private static DataSource dataSource;
private static ArrayList<Article> articleList = new ArrayList<>();

public static void selectArticle() {
           
    try {
        InitialContext ctx = new InitialContext();
        dataSource = (DataSource) ctx.lookup("jdbc/NemkeDB");
        Connection conn = dataSource.getConnection();
        String selectArticle = "select * from article where cart_id="+CartDAO.getAutoIncKey();// this is cart id
        PreparedStatement ps = conn.prepareStatement(selectArticle);
        ResultSet rs = ps.executeQuery(selectArticle);        
        while (rs.next()) {               
            int articleId = rs.getInt("id");
            String  articleTitle = rs.getString("title");
            double  articlePrice = rs.getDouble("price");
            double  articlePriceSum = rs.getDouble("priceSum");
            Article article = new Article(articleId, articleTitle, articlePrice,  articlePriceSum);
            articleList.add(article);
        }
    } catch (Exception e) {
        System.err.println(e);
    }
}

当用户每次点击按钮时,如何在不添加商品的情况下显示购物车?我只是为了显示它在我的数据库中的情况。

【问题讨论】:

  • 我更倾向于使用内存缓存来跟踪购物车中的商品,而不是每次添加商品时都会发出数据库请求。

标签: java mysql arraylist jdbc


【解决方案1】:

只需检查 ID 为 articleList 的文章是否已在您的列表中 - 如果是,请不要将其添加到列表中。

【讨论】:

猜你喜欢
  • 2021-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-16
相关资源
最近更新 更多