Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Assuming you're working with Swing (i.e. <code>JComboBox</code> and <code>JTextField</code>).</p> <p>You are not assigning the values to the <code>?</code> variables correctly. First, <code>AuthorID</code> is an integer and you need to assign the ID of the author, not the selected text.</p> <p>One way to go around it is to create your own simple class to hold ID and name of an author, with the corresponding <code>toString()</code> method:</p> <pre><code>class OneAuthor extends AbstractMap.SimpleEntry&lt;Integer, String&gt; { public OneAuthor(Integer id, String name) { super(id, name); } public String toString() { return getValue(); } } </code></pre> <p>Then, when you're populating your <code>JComboBox</code> with authors' names, use this class instead of String:</p> <pre><code>ResultSet rs = con.createStatement().executeQuery("SELECT id, name FROM authors ORDER BY name"); while(rs.next()) { author_names_combo.addItem(new OneAuthor(rs.getInt(1), rs.getString(2)); } </code></pre> <p>And then you can easily specify the correct author's ID:</p> <pre><code>pst.setInt(1, ((OneAuthor)author_name_combo.getSelectedItem()).getKey()); </code></pre> <p>Second, instead of using <code>getSelectedText()</code>, you need to use <code>getText()</code> method on the book title text field. <code>getSelectedText()</code> will only return the text highlighted in the field, while <code>getText()</code> will return the whole text. Thus, your full code will be something like this:</p> <pre><code>pst = con.prepareStatement(sql); pst.setInt(1, ((OneAuthor)author_name_combo.getSelectedItem()).getKey()); pst.setString(2, book_name.getText()); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload