在数据库中保存多个复选框值

时间:2018-06-18 07:04:20

标签: java html jsp servlets

我试图在mysql数据库中保存多个复选框值,我搜索了很多,但得到了如何在屏幕上打印选中的复选框,但我没有找到如何将选中的多个复选框保存到数据库中。

我的数据库结构是,如果用户选择了多个爱好,我创建了一个列为Hobbies,它们都应该保存在一列(Hobbies)

这是我的代码: HTML:

<table >

<tr>
<td width="26%">Hobbies</td>
<td ><input type="checkbox" name="Hobbies" value="Drawing">Drawing</td>
<td><input type="checkbox" name="Hobbies" value="Singing" >Singing</td>
<td ><input type="checkbox" name="Hobbies" value="Dancing" >Dancing</td>
<td ><input type="checkbox" name="Hobbies" value="Sketching" >Sketching</td>
</tr>
</table>

的Servlet

String Hobbies[]=request.getParameterValues("Hobbies");
for(String hb : Hobbies) {
    String s=hb;
}   //taking data from html
ps.setString(13,s); // Inserting into database
// At this line im getting as "s cannot be resolved to a variable"

1 个答案:

答案 0 :(得分:1)

您的错误*无法解析为变量“由于您在声明和定义它的循环之外引用变量而发生。

请执行以下操作:

String Hobbies[]=request.getParameterValues("Hobbies");
for(String hb : Hobbies) {
    // assuming ps.setString() inserts strings into your db
    ps.setString(13,hb);
}

更新/编辑

要确保使用单独的索引存储每个值,请为循环创建更新索引:

String Hobbies[]=request.getParameterValues("Hobbies");
// create your index starting at the position for the first hobby
int hobbyIndex = 13; // assuming you want to start storing at index 13
for(String hb : Hobbies) {
    // assuming ps.setString() inserts strings into your db
    ps.setString(hobbyIndex,hb);
    hobbyIndex++;
}

另一个更新/编辑

如果您只想以分号String分隔所有爱好,请执行

String[] Hobbies=request.getParameterValues("Hobbies");
// create your index starting at the position for the first hobby
int hobbyIndex = 13; // assuming you want to store all the hobbies at index 13
StringBuilder sb = new StringBuilder();
for(int i = 0; i < Hobbies.length; i++) {
    // push each hobby into a string builder at the end
    if (i == (Hobbies.length - 1)) {
        // do not append a semicolon after the last hobby
        sb.append(Hobbies[i];
    } else {
        // append the hobby and a semicolon
        sb.append(Hobbies[i]);
        sb.append(";");
    }
}
ps.setString(hobbyIndex,sb.toString());

我希望这有助于或让您了解如何实现您的需求。