I have the following sql tables:
Authors:
Id Name
2 John Smith
Books:
Id AuthorID Title
1 2 Shreak
I am trying to add more books to the books table through a GUI which has a drop down box to display the authors from the authors table and a textbox for entry of new book and a save button. The followiing is that correspond to the save button:
pprivate void save_bookActionPerformed(java.awt.event.ActionEvent evt) {
try {
String sql = "INSERT into books (AuthorId,Title) VALUES (?,?)";
pst = con.prepareStatement(sql);
pst.setInt(1, author_name_combo.getSelectedItem());
pst.setString(2, book_name.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "New Book has been added");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
private void FillCombo(){
try {
con = DriverManager.getConnection(url, user, password);
String sql = "SELECT * FROM Authors";
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()) {
String author = rs.getString("Name");
author_name_combo.addItem(author);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
I am a beginner and im struggling to populate the table with new data. the progamme compiles but the books table display NULL for Both AUTHOR ID and TITLE. how do I populate the table correctly so that author Id is automatically looked up from Authors table and given the approprate id number from there. please note author id is foreign key in books table.
Assuming you’re working with Swing (i.e.
JComboBoxandJTextField).You are not assigning the values to the
?variables correctly. First,AuthorIDis an integer and you need to assign the ID of the author, not the selected text.One way to go around it is to create your own simple class to hold ID and name of an author, with the corresponding
toString()method:Then, when you’re populating your
JComboBoxwith authors’ names, use this class instead of String:And then you can easily specify the correct author’s ID:
Second, instead of using
getSelectedText(), you need to usegetText()method on the book title text field.getSelectedText()will only return the text highlighted in the field, whilegetText()will return the whole text. Thus, your full code will be something like this: