1

I have a java program that will take a student's name from one table and join it with a classname and class_id from another table. I want the student_name,classname,and class_id to be written to a join table and saved in MySQL. Do I need to create a join table or can it be done through a SELECT statement?

This is what I have so far:

The students table has 3 columns: student_id, student_name, and hometown and the classes table has 3 columns: class_id, classname, description.

ResultSet rs3 = myStmt3.executeQuery("SELECT * FROM ClassSelector.classes WHERE class_id = " + selectedClass);
    while(rs3.next()){
                            String innerJoin = (userEnterId + " has been added to " + rs3.getString("classname") + " " + rs3.getString("class_id"));
                            System.out.println(innerJoin);
                            String student_classJoin = "INSERT INTO students" + "(student_name, class_id, classname)" + "VALUES (?, ?, ?)";
                            PreparedStatement pStmt = con.prepareStatement(student_classJoin);
                            pStmt.setString(1, userEnterId);
                            pStmt.setString(2, rs2.getString("class_id"));
                            pStmt.setString(3, rs2.getString("classname"));
                            pStmt.executeUpdate();
                            input.close();
                        }
Rassisland
  • 169
  • 1
  • 3
  • 16
  • It seems that you're missing a table, otherwise how would you know which students are in which classes? – Andreas Mar 01 '16 at 00:00
  • Are all tables in the same database? If so, you don't need to read the data into your application and write them back to db. You can do in the db directly. http://stackoverflow.com/a/7483174/5974819 – Awita Mar 01 '16 at 00:11
  • Yes, I have two tables in the same database. I'm trying to get it so a user can select or create a student, select a class, and add that student to the class and write student_name, class_id, and classname to a table. – Rassisland Mar 01 '16 at 00:17
  • any ideas? could it be the prepared statement? – Rassisland Mar 01 '16 at 00:46
  • So the question is how you can link students to classes in the db? – Awita Mar 01 '16 at 01:10
  • I want to link the selected student with the selected class in a separate table – Rassisland Mar 01 '16 at 01:16
  • Please show your tables and/or doublecheck your code. Either I am missing something or your code doesn't really match your description of the tables. Why do you want to insert the joined data into the students table and what is the userEnterId and rs2? – Awita Mar 01 '16 at 01:41

0 Answers0