尝试在Web应用程序上添加“按流派搜索”,但不知道代码有什么问题

问题描述 投票:0回答:1
java sql sqlite
1个回答
0
投票

首先你可以直接赋值

<button class="btn btn-outline-secondary" type="submit" name="gnr" value="Fantasy">Fantasy</button>
<button class="btn btn-outline-secondary" type="submit" name="gnr" value="Action">Action</button>
<button class="btn btn-outline-secondary" type="submit" name="gnr" value="FPS">FPS</button>

此外,您将在执行第一个查询后关闭数据库连接

public List<Item> findByKeyword(ServletContext context, String word, String genre) {
    List<Item> result = new ArrayList<>();

    try {
        Class.forName("org.sqlite.JDBC");

        String url = "jdbc:sqlite:" + context.getRealPath("WEB-INF/webapp.db");
        Connection conn = DriverManager.getConnection(url);

        String sql;
        PreparedStatement stmt;

        if (genre != null && !genre.isEmpty()) {
            sql = "select * from games where Genre like ? order by GameID";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, "%" + genre + "%");
        } else {
            sql = "select * from games where GameName like ? order by GameID";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, "%" + word + "%");
        }

        ResultSet rs = stmt.executeQuery();

        while (rs.next()) {
            Item item = new Item();
            item.setItemId(rs.getInt("GameID"));
            item.setItemName(rs.getString("GameName"));
            item.setGenre(rs.getString("Genre"));
            item.setDescription(rs.getString("Description"));
            item.setImage(rs.getString("GameCover"));
            item.setPrice(rs.getInt("Price"));
            item.setLink(rs.getString("Link"));
            result.add(item);
        }
        conn.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return result;
}
© www.soinside.com 2019 - 2024. All rights reserved.