将多个选定值插入表(oracle)

时间:2012-02-24 14:21:19

标签: java sql oracle jsp

这是我的 index.jsp 页面

<form action="addCountry.jsp" method="get">
    <select id="countries" class="multiselect" multiple="multiple" name="countries">
      <option value="AFG">Afghanistan</option>
      <option value="ALB">Albania</option>
      <option value="DZA">Algeria</option>
      <option value="AND">Andorra</option>
      <option value="ARG">Argentina</option>
      <option value="ARM">Armenia</option>
      <option value="ABW">Aruba</option>
      <option value="AUS">Australia</option>
      <option value="AUT" selected="selected">Austria</option>
      <option value="AZE">Azerbaijan</option>
      <option value="BGD">Bangladesh</option>
      <option value="BLR">Belarus</option>
      <option value="BEL">Belgium</option>
      <option value="BIH">Bosnia and Herzegovina</option>
      <option value="BRA">Brazil</option>
      <option value="BRN">Brunei</option>
      <option value="BGR">Bulgaria</option>
      <option value="CAN">Canada</option>
      <option value="CHN">China</option>
      <option value="COL">Colombia</option>
      <option value="HRV">Croatia</option>
      <option value="CYP">Cyprus</option>
      <option value="CZE">Czech Republic</option>
</select>
<br/>
      <input type="submit" value="Submit Form"/>
    </form>

这将是我的 addCountry.jsp 页面代码

<% 
try{
String[] country=request.getParameterValues("countries");
int count=0;
while(country[count]!=null)
out.println(country[count++]);
}catch(Exception ex)
{
//out.print(ex);
}
%>

但是,我很困惑同时将多个值插入表中。我应该使用循环多次插入?任何帮助赞赏!!在此先感谢!!

2 个答案:

答案 0 :(得分:2)

查看javadoc java.sql.Statement具体addBatch(String sql)executeBatch()方法,对语句进行排队,然后再一起执行。

答案 1 :(得分:0)

addCountries(request.getParameterValues("countries"));    

以下方法启动一个事务,一次执行一个查询,如果它们都成功则提交,如果有任何错误则回滚。

private void addCountries(String[] countries)
{
    Connection cn = <YOUR_CONNECTION_HERE>;

    try
    {
        // Require Explicit Commit
        cn.setAutoCommit(false);

        // Construct Query
        String  sql = "insert into countries " 
                + "  (country_code) " 
                + "values " 
                + "  (?) ";

        // For each country
        for(String country:countries)
        {
            PreparedStatement ps = cn.prepareStatement(sql);
            ps.setString(1, country);
            ps.executeUpdate();
            ps.close();
        }

        // Explicitly Commit - This point reached with no Exceptions.
        cn.commit();
    }
    catch (Exception e)
    {
        // Explicitly Rollback - There were errors along the way
        cn.rollback();
        e.printStackTrace();
    }
    finally
    {
        if(cn != null)
        {
            cn.close();
        }
    }
}

捕获Exception是不好的定制,因此我建议更改该部分以捕获抛出的任何单个异常类型,可能是SQLException等。