从JSP站点中选择条目,使用SQL和JDBC从数据库中删除条目

时间:2012-04-30 19:05:35

标签: java jsp jdbc

我需要一些帮助来创建一个删除SQL数据库中的条目/行的方法。我使用JBDC,JSP和java。我已经有一个适用于我的JSP站点的add方法。问题是我不确定是否需要创建一个对象才能使其工作。这是我到目前为止的代码JSP(removeMatch.jsp):

    <div class="content">

    <%
        String databaseId = request.getParameter("id");
        String matchDate = request.getParameter("matchDate");
        String matchTime = request.getParameter("matchTime");
        String meetingTime = request.getParameter("meetingTime");
        String series = request.getParameter("series");
        String opponent = request.getParameter("opponent");
        String matchLocation = request.getParameter("matchLocation");


        if (matchDate != null && matchTime != null && meetingTime != null && series != null && opponent != null && matchLocation != null) {
            int intSeries = Integer.parseInt(series);
            Match match = new Match(matchDate, matchTime, meetingTime, intSeries, opponent, matchLocation);

            //cast string to long value
            long longDatabaseId = Long.parseLong(databaseId);
            match.setDatabaseId(longDatabaseId);

            //remove the match
            MatchMapper.removeMatch(match);

            //Test in console, they don't print the same values that are connected to the databaseId:
                System.out.println(databaseId);
                System.out.println(matchDate);
                System.out.println(matchTime);
                System.out.println(meetingTime);
                System.out.println(series);
                System.out.println(opponent);
                System.out.println(matchLocation);
        }
    %>

    <h3>Vælg de kampe som du vil slette og dermed fjerne fra
        databasen:</h3>
    <form action="removeMatch.jsp" method="post">
        <fieldset>
            <table border="1">
                <tr>
                <!-- TABEL PASSER IKKE OVER ENS!!!! -->

                    <th></th>
                    <th>Dato</th>
                    <th>Modstander</th>
                    <th>Spilletid</th>
                    <th>Mødetid</th>
                    <th>Spillested</th>
                    <th>Serie</th>
                </tr>
                <%
                    ArrayList<Match> matches = MatchMapper.getAllMatches();
                    for (Match m : matches) {
                %>
                <tr>
                    <td><input type="checkbox" name="id" value=<%=m.getDatabaseId()%>></td>
                    <td><input type="hidden" name="matchDate" value=<%=m.getDate()%>><%=m.getDate()%></td>
                    <td><input type="hidden" name="matchTime" value=<%=m.getMatchStart()%>><%=m.getMatchStart()%></td>
                    <td><input type="hidden" name="meetingTime" value=<%=m.getMeetingTime()%>><%=m.getMeetingTime()%></td>
                    <td><input type="hidden" name="series" value=<%=m.getSeries()%>><%=m.getSeries()%></td>
                    <td><input type="hidden" name="opponent" value=<%=m.getOpponent()%>><%=m.getOpponent()%></td>
                    <td><input type="hidden" name="matchLocation" value=<%=m.getLocation()%>><%=m.getLocation()%></td>
                </tr>
                <%
                    }
                %>
            </table>

            <a href="matchTable.jsp"><input type="submit" value="Slet Kampe" /></a>

        </fieldset>
    </form>
</div>

这个想法是用户检查他想要删除的行,然后另一个java文件中的方法删除数据库中的行(removeMatch()@ MatchMapper.java):

    public static void removeMatch(Match match) {
    Connection con = null;
    try {
        con = JDBCConnectionFactory.getInstance().getNewConnection();
        // creates empty string
        String sql = "";
        // if Match  exists in database, then prepare to call
        // a DELETE FROM table_name WHERE some_column=some_value statement (matchDate and opponent)
        if (match.isInDatabase()) {
            sql = "DELETE FROM matches WHERE ID = ?) "
                    + "VALUES (?)";
        }
        // if Match doesn't exist in database, then prepare to make an
        // return 
        else {
            System.out.println("Kamp findes ikke i databasen");
        }

        PreparedStatement prep = con.prepareStatement(sql);
        prep.setLong(1, match.getDatabaseId());
        // if the match already exists in database, then get the id (so it
        // won't create a new id)
        if (match.isInDatabase()) {
            prep.setLong(2, match.getDatabaseId());
        }
        // execute insert/update
        prep.executeUpdate();

    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        JDBCConnectionFactory.getInstance().closeConnection(con);
    }

}

我可以获得正确的databaseId,但是我的测试打印到控制台继续使用databaseId“1”打印行的值。可能有一种方法可以传递正确的值,但我无法弄明白。另一个问题是removeMatch不会删除匹配,事实上,它不会对数据库进行任何更改。

1 个答案:

答案 0 :(得分:0)

首先,您的DELETE sql看起来不对:

sql = "DELETE FROM matches WHERE ID = ?) " // Why is there a closing parenthesis?
          + "VALUES (?)";      // Why are you using VALUES in a DELETE?

我会用

sql = "DELETE FROM matches WHERE ID = ? ";

这将消除对这些行的需求:

if (match.isInDatabase()) {
    prep.setLong(2, match.getDatabaseId());
}

最后,为了解决您没有对数据库进行任何更改的问题,我将结束您的try块:

con.commit();

如果您将自动提交设置为true,则可能不需要这样做。我并不是要批评你,但似乎这是你第一次编写JDBC代码。如果是这种情况,我强烈建议您浏览this tutorial。它为您提供了JDBC原则的所有基本解释。