This week, find out how to connect your JSPs to a database and build dynamic, data-driven Web pages. This primer covers different techniques to select, insert and delete records, and uses a simple Web-based address book to illustrate the Connection, Statement, and ResultSet objects.
If you examine it closely, you'll see that this form performs
a query to retrieve the list of users currently available in the system, and uses this data to generate a list box containing the different user names. This makes it possible to specify the owner of each record when it is INSERTed.
Once the form has been filled up and submitted, control passes to "add_res.jsp", which takes care of actually performing the INSERT operation. Take a look.
This example demonstrates yet another method of the Statement
object, the executeUpdate() method, used for INSERT or UPDATE operations. This method returns a result code indicating the number of rows affected by the operation - in case of the example above, this result code should be 1. In case it isn't...you've got trouble!
It should be noted at this point that if your INSERT statement contains special characters which need to be escaped (say, commas or single quotes), you'd do better to use the PreparedStatement class, which automatically takes care of escaping special characters and offers some performance benefits as well. A discussion of the PreparedStatement class is beyond the scope of this tutorial, but there's plenty of documentation out there should you ever require it.