使用jsp在数据库中插入多行

时间:2018-08-22 17:32:04

标签: mysql angularjs jsp jdbc

当前,我正在使用Angularjs,JSP和MySQL进行简单的CRUD操作。我正在使用Angularjs从WEB API中获取数据,但是我成功了,但是当我插入多行时,它只会多次插入第一行数据,而不是第二,第三等等。因此,我想在数据库中插入所有行,请帮帮我。 我的代码是 FetchData.jsp

<!DOCTYPE html>
<html >
<style>
table, th , td  {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
 background-color: #f1f1f1;
    }
  table tr:nth-child(even) {
    background-color: #ffffff;
   }
</style>
<script    src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<form action="jdbc.jsp" method="post"> 
<div ng-app="myApp" ng-controller="customersCtrl">

<table>
  <tr ng-repeat="x in names">
   <td><input type="text" value="{{ x.state_id }}" name="stid"/>  </td> 
    <td> <input type="text" value=" {{ x.state_name}}" name="stname"/> </td>
   <td> <input type="text" value=" {{ x.state_location}}" name="stct"/> </td>
     <td><input type="text" value="{{ x.country_id}}" name="ctid"/></td>
        <td><input type="submit" value="submit"></td>

    </tr>

     </table>

    </div>

   </form>
  <script>
  var app = angular.module('myApp', []);
 app.controller('customersCtrl', function($scope, $http) {
     $http.get("https://www.boappa.se/api/state/")
         .then(function (response) {$scope.names = response.data;});
      });
     </script>

      </body>
      </html>

jdbc.jsp

  <html>
      <head>
         <title>json data</title>
     <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
       </head>


       <%@ page import="javax.servlet.*" %>
       <%@ page import="javax.servlet.http.*" %>
         <%@ page import="java.sql.*" %>

      <%
      String stid = request.getParameter("stid");
      String statename = request.getParameter("stname");
      String statecon = request.getParameter("stct");
      String conid = request.getParameter("ctid");

       Connection connection = null;
        PreparedStatement pstatement = null;

        Class.forName("com.mysql.jdbc.Driver").newInstance();
           int j=0;

       try {
        connection = DriverManager.getConnection        ("jdbc:mysql://localhost:3306/youtube","root","root");
    String queryString = "INSERT INTO jsondata   (id,state_id,state_name,state_country,country_id) VALUES (?,?, ?, ?,?)";
      pstatement = connection.prepareStatement(queryString);
       pstatement.setString(1, stid);
     pstatement.setString(2, stid);
     pstatement.setString(3, statename);
     pstatement.setString(4, statecon);
     pstatement.setString(5, conid);
    for(int i=0;i<=21;i++){
     j=pstatement.executeUpdate();
    j++;
  }
  } 
   catch (Exception ex) {
   out.println("Unable to connect to database.");
  }
  finally {
 pstatement.close();
   connection.close();

    }
   %>

    </body>
    </html>

0 个答案:

没有答案