0

I am trying to insert the last added id of my chapter table to the lesson table.

Here is my code:

String Sql = "INSERT INTO lesson" +"(title, chapter_id, source)" +"VALUES(?,?,?)"; String getId = "SELECT MAX(id) AS id FROM chapter"; rs = pst.executeQuery(getId); int lastid = rs.getInt("id"); rs.close(); pst=conn.prepareStatement(Sql); pst.setString(2,txt_lessonTitle.getText()); pst.setInt(3,lastid); pst.setString(4,txt_lessonContent.getText()); pst.executeUpdate(); 

I got an error:

Before start of result set

3 Answers 3

2

You need to check whether there are some results

rs = pst.executeQuery(getId); if (rs.next()) { int lastid = rs.getInt("id"); rs.close(); pst=conn.prepareStatement(Sql); pst.setString(2,txt_lessonTitle.getText()); pst.setInt(3,lastid); pst.setString(4,txt_lessonContent.getText()); pst.executeUpdate(); } 
Sign up to request clarification or add additional context in comments.

2 Comments

the correct statement is you need to move the cursor to first row as by defautl a ResultSet cursor is initially positioned before the first row
to set index of params you should start from 1 not 2 this can cause an error :)
0

Try this:

int lastid; rs.afterLast(); while (rs.previous()) { lastid = rs.getInt("id"); } rs.close(); // other code statements can be here 

Comments

0

Thank you guys!. .my error is here:

 pst.setString(2,txt_lessonTitle.getText()); pst.setInt(3,lastid); pst.setString(4,txt_lessonContent.getText()); 

instead of using

 pst.setString(1,txt_lessonTitle.getText()); pst.setInt(2,lastid); pst.setString(3,txt_lessonContent.getText()); 

thanks for your answer and suggestions it gives me the answer.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.