title: How to retrive specific data from a SQL database with JDBC?
body: <p>I've created a SQL-database containing three tables: Student, Course, Studies. I have no problem adding and retrieving information from/to student and course but when I try to do the same with Studies I get som problems. I've narrowed it down to the segment shown below. The problem is that I can add a student that does not exist in the Studies-table (but does exist in the Student &amp; course tables) without a problem. But if I already have a student that's in the studies table and I wan't to add another entry (i.e. a student who studies more then one course) I get nothing. I've tried bypassing it with numerous loops and methods outside the codesegment, but nothing works. I'm pretty sure I'm close to the answer but I need help to get to the end. Any help is appreciated.</p>
  
  <pre><code>public void saveStudies() throws SQLException {
  
      String checkSql = "select count(*) as count from studies where spnr=?";
      PreparedStatement checkStmt = con.prepareStatement(checkSql);
  
      String insertSql = "insert into studies (spnr, cid) values (?, ?)";
      PreparedStatement insertStmt = con.prepareStatement(insertSql);
  
      for(Studies studies: studiess) {
          int spnr = studies.getSpnr();
          int cid = studies.getCid();
  
          checkStmt.setInt(1, spnr);
  
          ResultSet checkResult = checkStmt.executeQuery();
          checkResult.next();
  
          int count = checkResult.getInt(1);
  
          if(count == 0) {
  
              System.out.println("Inserting student with pnr: " + spnr + " into course with cid: " + cid);
  
              insertStmt.setInt(1, spnr);
              insertStmt.setInt(2, cid);
  
              insertStmt.executeUpdate();
          }
          else {
              System.out.println("A message containing information that says that the student and or course does not exist in the database");
          }
  
      }
  
      insertStmt.close();
      checkStmt.close();
  }
  </code></pre>