delete multiple rows in one statement in jsp taking dynamic java variable
checkbox.jsp
<form action="test.jsp">
<input type="checkbox" name="id" value="Java"> Java<br>
<input type="checkbox" name="id" value=".NET"> .NET<br>
<input type="checkbox" name="id" value="PHP"> PHP<b开发者_开发知识库r>
<input type="checkbox" name="id" value="C/C++"> C/C++<br>
<input type="checkbox" name="id" value="PERL"> PERL <br>
<input type="checkbox" name="id" value="vb SCRIPT"> PERL <br>
<input type="submit" value="Submit">
</form>
test.jsp
<%
String select[] = request.getParameterValues("id");
if (select != null && select.length != 0) {
out.println("You have selected: ");
for (int i = 0; i < select.length; i++) {
out.println(select[i]);
}
}
String selected="";
StringBuffer sb = new StringBuffer();
for(int i = 0; i < select.length; i++) {
sb.append(select[i] + ",");
}
String vwarnid = sb.toString();
vwarnid = vwarnid.substring(0, vwarnid.length()-1);
out.print(vwarnid);
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c = DriverManager.getConnection("jdbc:odbc:Task","","");
Statement st = c.createStatement();
PreparedStatement pst = c.prepareStatement
("DELETE FROM checkdata WHERE name IN('"+vwarnid +"')");
int i=pst.executeUpdate();
out.print(i);
out.println("deleted");
} catch(Exception e) {
}
%>
when I select only one checkbox the value is getting deleted but not with multiple selection of checkboxes Can anyone help me out?
Your IN
clause should end up as
IN('Java','.NET','PHP')
but the way as you coded it, it ends up as
IN('Java,.NET,PHP')
which is obviously wrong.
Unrelated to the concrete problem, there are several serious issues in your code. Please sanitize your input from SQL injection attacks. Learn PreparedStatement
. Using IN
clause with PreparedStatement
is outlined in this answer. Also putting raw Java code in a JSP file isn't really the recommended practice. Learn servlets. Also ignoring exceptions isn't very helpful for the case you run in to trouble. Also the DB resources should be close()
d in finally
block.
Does this
SELECT * FROM checkdata WHERE name IN(('"+vwarnid+"'))");
return any rows ?
精彩评论