
[英]Updating the table created in JSP using the values sent from the form (No database)
[英]submit textbox values from html table to database using JSP
我有两个名为Trick1和Trick2的数据库表。
Trick1表
ID | 标准| 批量
21 | X | 乙
22 | X | 乙
23 | X | 乙
24 | X | 乙
25 | X | 乙
26 | X | 乙
Trick2表
ID | 标准| 批处理 分数
这是带有代码的HTML表,其中的数据是从Trick1数据库中获取的。表并创建带有文本框的称为MARKS的新列,并重定向至页面tableDemo2.jsp。
<form method="post" action="tableDemo2.jsp">
<table style="border : 1px solid blue;">
<tr>
<th>ID</th>
<th>STD</th>
<th>BATCH</th>
<th>MARKS</th>
</tr>
<%
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/mcc", "root","");
String query = "select * from trick1";
Statement stmt = (Statement) con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
%>
<tr>
<td><%=rs.getString("id") %></td>
<input type="hidden" name="ids" value="<%=rs.getString("id")%>">
<td><%=rs.getString("std") %></td>
<input type="hidden" name="stds" value="<%=rs.getString("std")%>">
<td><%=rs.getString("batch") %></td>
<input type="hidden" name="batchs" value="<%=rs.getString("batch")%>">
<td><input type="number" name="numb"></td>
</tr>
<%
} }
catch(SQLException se){
System.out.println("SQL Exception : "+se.getMessage());
}
%>
</table>
<input type="submit" value="Submit" name="submit">
</form>
这是用HTML创建的表
我想要的是,HTML表的所有四列数据都应插入Trick2数据库表中
以下是表格tableDemo2.jsp
<%
String id = request.getParameter("ids");
String std = request.getParameter("stds");
String batch = request.getParameter("batchs");
String[] marks = request.getParameterValues("numb");
new ArrayList<String>(Arrays.asList(marks));
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/mcc", "root","");
Statement stmt = (Statement) con.createStatement();
stmt.executeUpdate("insert into trick2 values('"+id+"','"+std+"','"+batch+"','"+marks+"')");
response.sendRedirect("tableDemo.jsp");
}
catch(SQLException se) {
System.out.println("SQL Exception : "+se.getMessage());
}
%>
我哪里做错了。 请帮我。 谢谢。
首先,您应该在.jsp文件中完全避免数据库设置和数据库代码。 这应该转到服务器端。
阅读有关jstl的信息,以避免服务器端与前端混用。
我看到您正在尝试获取ID,但正在使用
String ids = request.getParameter("ids")
您应该使用与标记相同的标记
String[] ids = request.getParameterValues("ids");
对要获取值的其他变量执行相同的操作。
还请阅读有关SQL注入的信息,以了解为什么此行不安全:
stmt.executeUpdate("insert into trick2 values('"+id+"','"+std+"','"+batch+"','"+marks+"')");
为此使用PreparedStatemnt:
String SQL_INSERT = "INSERT INTO EMPLOYEE (NAME, SALARY, CREATED_DATE) VALUES (?,?,?)";
PreparedStatement preparedStatement = conn.prepareStatement(SQL_INSERT)) {
preparedStatement.setString(1, "mkyong");
preparedStatement.setBigDecimal(2, new BigDecimal(799.88));
preparedStatement.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));
preparedStatement.executeUpdate();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.