Sample JDBC PreparedStatement (using SQL UPDATE)

By Alvin J. Alexander, devdaily.com

Here's a sample Java method that performs a JDBC SQL UPDATE using a PreparedStatement. If you've never used a PreparedStatement before when accessing a database I hope this serves as a decent example to get you started.

public static void updateDescriptionAndAuthor (Connection conn,
                                               String description,
                                               int id,
                                               int seqNum,
                                               String author )
throws SQLException
{
  try
  {
    PreparedStatement ps = conn.prepareStatement(
      "UPDATE Messages SET description = ?, author = ? WHERE id = ? AND seq_num = ?");
    ps.setString(1,description);
    ps.setString(2,author);
    ps.setInt(3,id);
    ps.setInt(4,seqNum);
    ps.executeUpdate();
    ps.close();
  }
  catch (SQLException se)
  {
    // log the exception
    throw se;
  }
}

devdaily logo