2013-05-14 45 views
1

我正嘗試使用jsp頁面中的複選框刪除數據庫中的記錄。對JSP和前端來說是新手,所以我無法正確調試並找出我應該如何實際執行它。需要刪除數據庫中的記錄並提醒使用jsp中的複選框刪除的ID

<%@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> 

回答

0

您已經在JSP中獲得了scriptlet代碼。這是一個非常糟糕的主意。

我建議學習JSTL並讓JSP與servlet通信。該servlet將綁定和驗證輸入參數並與執行數據庫操作的對象進行交互。

關於這種安排的好處是,它自然地將您的問題分解成碎片。數據庫可以被編碼,調試,測試並放在一邊。

+0

你能幫我這段代碼plz – Aayush 2013-05-14 15:55:52

+0

我想我已經做到了。 – duffymo 2013-05-14 17:16:16