我想使用 JSP 在数据库的单列中存储多个复选框值,但在单行中存储单个值。 我的 JSP 代码 QuickFunction.jsp:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2 align="center"> Quick Function</h2>
<form action="QuickServlet">
<table border="1" align="center">
<tr><td width=50 align="center">1</td>
<td>Book A voucher</td>
<td>Sales Voucher</td>
<td><input type="checkbox" name="voucher"
value="Sales Voucher" /></td>
</tr>
<tr><td></td><td></td>
<td>Purchase Voucher</td>
<td><input type="checkbox" name="voucher"
value="Purchase Voucher" /></td>
</tr>
<tr><td></td><td></td>
<td>Receipt</td>
<td><input type="checkbox" name="voucher"
value="Receipt" /></td>
</tr>
<tr><td></td><td></td>
<td>Payment </td>
<td><input type="checkbox" name="voucher"
value="Payment" /></td>
</tr>
<tr>
<td></td><td></td><td> Contra </td>
<td><input type="checkbox" name="voucher"
value="Contra" /></td>
</tr>
<tr><td></td><td></td>
<td> Journal </td>
<td><input type="checkbox" name="voucher"
value="Journal"></td>
</tr>
</table>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
我的servlet代码QuickServlet(doGet方法):
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String voucher = "";
String a[]=request.getParameterValues("voucher");
for(int i=0;i<a.length;i++){
voucher+=a[i]+"";
}
DBConnection dbc=new DBConnection();
Connection con=dbc.getNewConnection();
Statement st = null;
ResultSet rs = null;
try
{
st = con.createStatement();
}
catch (SQLException e)
{
e.printStackTrace();
}
String updatecust = "insert into vouchers(voucher) values('"+voucher+"');";
try
{
int i=st.executeUpdate(updatecust);
if(i>0){
out.print(" saved successfully....!!");
}
else
out.print("Sorry..!! Got an exception.");
}
catch (SQLException e)
{
e.printStackTrace();
}
}
这将复选框值存储在单行单列中,如下所示:
mysql> select * from vouchers;
+--------------------------------------+
| voucher |
+--------------------------------------+
| Sales VoucherPurchase VoucherReceipt |
+--------------------------------------+
但我想将一个值存储在一行中,依此类推。如下(预期输出):
mysql> select * from vouchers;
+------------------+
| voucher |
+------------------+
| Sales Voucher |
| Purchase Voucher |
| Receipt |
+------------------+
请帮助我。提前致谢!!
最佳答案
在您的代码中,首先使用 for 循环连接所有凭证,然后插入。
如果您希望每个凭证按行插入,那么您可以在 for 循环中调用插入查询并插入凭证,而不是在 for 循环中串联凭证。
像这样:
for(int i=0;i<a.length;i++){
String updatecust = "insert into vouchers(voucher) values('"+voucher+"');";
}
关于mysql - 如何使用jsp在数据库的单行中插入多个复选框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28171246/