1

jsp ページのチェックボックスを使用してデータベースのレコードを削除しようとしています。私はJSPとフロントエンドが初めてなので、適切にデバッグして、実際にどのようにすべきかを知ることができません。

<%@page import="java.sql.*"%>

<form name=myname >
<table border="1">
<tr><td></td><a href="#" onclick='deleteElement();'">Delete</a>
<td><b><u>bookid</u></b></td>
<td><b><u>Author</u></b></td>
<td><b><u>title</u></b></td>
</tr>
<%try{
Connection conn = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "root");
ResultSet rs = null;
Statement st=null;
st=conn.createStatement();
rs = st.executeQuery("select * from book");

int i=0; while(rs.next()){ %>
<tr><td><input type="checkbox" name="check<%=i%>" value=<%= rs.getString("bookId") %>></td>
    <td><%= rs.getString("bookId") %></td>
    <td><%= rs.getString("author") %></td>
    <td><%= rs.getString("title") %></td>
</tr><%
i++;
}
}catch(SQLException e){ System.out.println(e.getMessage()); } %>
</table>
</form>
<script LANGUAGE="JAVASCRIPT">
function deleteElement(){
    alert("hello");
    <%String id[]= new String[10];
    for(int i=0;i<10;i++){
    id[i]=request.getParameter("check"+i);
    }
    %>
    <%try{
    Connection conn = null;
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "root");
    Statement st=null;
    st=conn.createStatement();
    for(int a=0;a<10;a++){
    st.executeUpdate("delete from book where bookid='"+id[a]+"'");
    }
    }catch(SQLException e){ 
        System.out.println(e.getMessage()); 
        }
        %>
}
</script>   
4

1 に答える 1

0

JSP にスクリプトレット コードがあります。それは非常に悪い考えです。

JSTL を学習し、JSP がサーブレットと通信できるようにすることをお勧めします。サーブレットは、入力パラメーターをバインドして検証し、データベース操作を実行するオブジェクトと対話します。

この配置の良いところは、問題を自然に分解できることです。データベースは、コーディング、デバッグ、テスト、および脇に置くことができます。

于 2013-05-14T15:48:26.680 に答える