“ JSP第一次连接导致结束时第二次连接未运行”

时间:2019-05-18 03:46:53

标签: mysql eclipse jsp

我正在尝试从两个不同的表(类型和游戏)中获取两个数据(GenreID和GameID),并将它们插入到另一个表(games_genre)中。但是,即使我已经创建了另一个新的数据库连接,在成功插入GenreID之后,它也会关闭与数据库的连接。

我尝试创建到同一数据库的connection1和connection2。 Connection1用于插入GenreID,connection2用于插入GameID

<%@ page import="java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat" %>
String gametitle = request.getParameter("gametitle");
String [] checkbox1 = request.getParameterValues("checkbox");

try {
   Class.forName("com.mysql.cj.jdbc.Driver");
   String connURL ="jdbc:mysql://localhost/assignment?user=root&password=root&serverTimezone=UTC"; 

   Connection conn = DriverManager.getConnection(connURL);
   Connection conn2 = DriverManager.getConnection(connURL);

   Statement stmt = conn.createStatement();   
   if (checkbox1!= null){
      for(String s: checkbox1){
       String sqlStr2 = "Select * FROM genre WHERE GenreName='" + s + "'";  
       ResultSet rs = stmt.executeQuery(sqlStr2);
       while(rs.next()){
          String genreid = rs.getString("GenreID");
          String sqlStr3 = "INSERT INTO games_genre(GenreID) VALUES ('" + genreid + "')";
          int j = stmt.executeUpdate(sqlStr3);  
          if (j>0) {
           out.println("Adding GenreID Successfully!");}
       }                
      }
   }
   conn.close();

   Statement stmt2 = conn2.createStatement();
   String sqlStr4 = "Select * FROM games WHERE GameTitle='" + gametitle +"'";
   ResultSet rs2 = stmt2.executeQuery(sqlStr4);
   if(rs2.next()){
      String gameid = rs2.getString("GameID");
      String sqlStr5 = "INSERT INTO games_genre(GameID) VALUES ('" + gameid + "')";
      int k = stmt2.executeUpdate(sqlStr5); 
      if (k>0) {
     out.println("Adding GameID Successfully!");            
      }
   }

   conn2.close();
} catch (Exception e) {
   out.println("Error :" + e);
}

成功添加游戏!成功添加GenreID!错误:java.sql.SQLException:ResultSet关闭后不允许进行操作

1 个答案:

答案 0 :(得分:0)

我不明白为什么您需要创建两个Connection,因为您需要访问相同的database。因此,只需创建多个Statement即可执行多个查询,如下所示:

    Statement stmt=null;
    Statement stmt2=null;
       try {
               Class.forName("com.mysql.cj.jdbc.Driver");
               String connURL ="jdbc:mysql://localhost/assignment?user=root&password=root&serverTimezone=UTC"; 
               Connection conn = DriverManager.getConnection(connURL);
                 stmt = conn.createStatement();   
               if (checkbox1!= null){
                ....
               }
            <!--using same conn object -->
            stmt2 = conn.createStatement();
               String sqlStr4 = "Select * FROM games WHERE GameTitle='" + gametitle +"'";
           ResultSet rs2 = stmt2.executeQuery(sqlStr4);
           if(rs2.next()){
             ...
           }
      <!--finally close connection-->
         conn.close();  

     } catch (Exception e) {
   out.println("Error :" + e);
}

注意 :还尝试使用 PreparedStatement 来防止将Sql Injection的值连接到查询字符串中,不安全的。