Java Reference
In-Depth Information
String recipe = rs.getString("RECIPE_NUM");
String name = rs.getString("NAME");
String desc = rs.getString("DESCRIPTION");
Once the column value has been obtained, you can do what you want to do with the
values you have stored within local variables. In this case, they are printed out using
the System.out() method.
System.out.println(recipe + "\t" + name + "\t" + desc);
A java.sql.SQLException could be thrown when attempting to query a
database (for instance, if the Connection object has not been properly obtained or if
the database tables that you are trying to query do not exist). You must provide excep-
tion handling to handle errors in these situations. Therefore, all database-processing
code should be placed within a try block. The catch block then handles a SQLEx-
ception , so if one is thrown, the exception will be handled using the code within the
catch block. Sounds easy enough, right? It is, but you must do it each time you per-
form a database query. Lots of boilerplate code.
It is always a good idea to close statements and connections if they are open. Using
the try-with-resources construct is the most efficient solution to resource man-
agement. Closing resources when finished will help ensure that the system can realloc-
ate resources as needed, and act respectfully on the database. It is important to close
connections as soon as possible so that other processes can use them.
13-4. Performing CRUD Operations
Problem
You need to have the ability to perform standard database operations within your ap-
plication. That is, you need the ability to create, retrieve, update, and delete (CRUD)
database records.
Solution
Create a Connection object and obtain a database connection using one of the solu-
tions provided in Recipe 13-1; then perform the CRUD operation using a
Search WWH ::




Custom Search