I've been playing around with the Learn With series and building the backend services in Java. I was going right along until I got to the chapter to create and update data. The query is something like this:

view plain print about
1String SQL = "insert into tasks(taskCategoryID, userID, description, completed, dateCreated) values(?,?, ?, 0, ? )

This is a super common approach to creating a new item in SQL Server, and then immediately selecting the newly created ID with SCOPE_IDENTITY(). I'd expect it to work easily.

The rest of the code:

view plain print about
1PreparedStatement pstmt = connection.prepareStatement(SQL);
3// set parameters
4pstmt.setInt(1, taskCategoryID);
5pstmt.setInt(2, userID);
6pstmt.setString(3, description);
7LocalDate dateCreated = LocalDate.now();
8pstmt.setObject(4, dateCreated);
9ResultSet rs = pstmt.executeQuery();

The last line will throw an error claiming that the query returned no results sets and blow up. I had been swimming along smoothly until I ran into that issue. It turns out that, for updates and inserts, that is the wrong approach. Instead of using executeQuery(), I need to use executeUpdate(), like this:

view plain print about

After that, I can get the second result set using this:

view plain print about
1ResultSet rs = pstmt.getGeneratedKeys();

Then things are good to go.

You'll probably find the LearnWith series supporting Java next month.