使用 JSP 将多个 HTML 行值保存到 MySQL



在 html 页面上单击<button> btnSave时,将调用saveRecords.jsp来保存 HTML 的多行。saveRecords.jsp中的代码如下。

try{
        String[] table_id = request.getParameterValues("table_id");   
        String[] hall_name = request.getParameterValues("hall_name");
        String[] hall_capacity = request.getParameterValues("hall_capacity");   
        Class.forName("com.mysql.jdbc.Driver");  // MySQL database connection
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/chbs?" + "user=root&password=");    
        PreparedStatement pst = conn.prepareStatement("INSERT INTO `halls`(`Hall_ID`, `Hall_Name`, `Capacity`) VALUES (?, ?, ?);");
        pst.setString(1, table_id);
        pst.setString(2, hall_name);
        pst.setString(3, hall_capacity);
        int rset = pst.executeUpdate();       
    }

但是,PreparedStatement.setString(( 不接受 Array。由于 HTML 表在一个.jsp中,而保存 HTML 行值的代码saveRecords.jsp不同,因此HTML table值不会被发布,并且PreparedStatement.setString()抛出错误。正确的方法是什么?

您需要批量更新。 假设值经过验证并且数组长度相等,您可以在末尾addBatch每个插入和executeBatch;

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/chbs?" + "user=root&password=");    
String sql = "INSERT INTO `halls`(`Hall_ID`, `Hall_Name`, `Capacity`) VALUES (?, ?, ?);";
PreparedStatement ps = conn.prepareStatement(sql);
for (int i=0; i< table_id .length;i++) {
   ps.setString(1, table_id [i]);
   ps.setString(2, hall_name [i]);
   ps.setString(3, hall_capacity [i]);
    ps.addBatch();
}
ps.executeBatch();
try{
        String[] table_id = request.getParameterValues("table_id");   
        String[] hall_name = request.getParameterValues("hall_name");
        String[] hall_capacity = request.getParameterValues("hall_capacity");   
        Class.forName("com.mysql.jdbc.Driver");  // MySQL database connection
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/chbs?" + "user=root&password=");    
        PreparedStatement pst = conn.prepareStatement("INSERT INTO `halls`(`Hall_ID`, `Hall_Name`, `Capacity`) VALUES (?, ?, ?);");
for(int i=0;i<table_id.lenght;i++){
        pst.setString(1, table_id[i]);
        pst.setString(2, hall_name[i]);
        pst.setString(3, hall_capacity[i]);
        int rset = pst.executeUpdate();       
    }
}

它也将为您工作。

最新更新