Java PreparedStatement - a SQL UPDATE example

Java PreparedStatement FAQ: Can you provide a Java PreparedStatement example?

Here's a sample method that performs a JDBC SQL UPDATE using a Java PreparedStatement. If you've never used a Java PreparedStatement before when accessing a database, or you're an experienced programmer who just needs a Java PreparedStatement example, I hope this serves as a decent example to get you started.

// a java preparedstatement example
public static void updateDescriptionAndAuthor (Connection conn,
                                               String description,
                                               int id,
                                               int seqNum,
                                               String author )
throws SQLException
{
  try
  {
    // create our java preparedstatement using a sql update query
    PreparedStatement ps = conn.prepareStatement(
      "UPDATE Messages SET description = ?, author = ? WHERE id = ? AND seq_num = ?");

    // set the preparedstatement parameters
    ps.setString(1,description);
    ps.setString(2,author);
    ps.setInt(3,id);
    ps.setInt(4,seqNum);

    // call executeUpdate to execute our sql update statement
    ps.executeUpdate();
    ps.close();
  }
  catch (SQLException se)
  {
    // log the exception
    throw se;
  }
}

I'll skip the description of this Java PreparedStatement UPDATE example for now, but if you have any questions or comments, just leave them below, and I'll be glad to respond to them.

GREAAAAAAAAAAAAT ! Thnxs

GREAAAAAAAAAAAAT ! Thnxs

Post new comment

The content of this field is kept private and will not be shown publicly.