Java Reference
In-Depth Information
These three operations correspond to JDBC objects for doing these very
things, namely the classes Connection , PreparedStatement , and ResultSet .
Let's jump right in and look at some code. Example 15.1 will make a
connection to a MySQL database, prepare a query statement, execute the query,
then read up the results.
Let's also look at a similar example, but this time for an Oracle database
(Example 15.2). Notice how much is the same between the two examples, and
which parts are different.
The only real difference between the two programs has to do with the
connections. Once the connection to the database is established, the rest of the
code is exactly the same—which is what you'd hope for in an abstraction. This
is a good news for developers: “Learn once, use anywhere.”
15.3
M AKING C ONNECTIONS
The most complicated part of JDBC is establishing the connection. There are
several ways to make a connection, depending on how much information about
the connection driver you want hard-coded into your application. We are going
to keep it simple and describe one straightforward way to connect.
The DriverManager class is where our application goes to get its
connection to the database, as shown in our example. Many different JDBC
drivers can register with the DriverManager , and it can make the
connection to the kind of driver that you want based on the URL that you
provide in the call to getConnection() . So where did our example register
anything with the DriverManager ? Well, it happened indirectly, via the
Class.forName(...).newInstance(); call. That loaded the class and cre-
ated an instance of it. The JDBC specification says that when a Driver class
initializes it must register with the DriverManager . So it happened “under the
covers,” in loading the driver class.
Another difference between the two examples deals with how the username
and password are supplied to the database. Both are supplied in the URL,
though in different syntax. That syntax is at the discretion of those who imple-
mented the JDBC driver for that particular flavor of database. If we were to
construct the URL at runtime, so that the user could supply a username and
password dynamically, we'd want to remove the difference in how the URL is
constructed. To do that we could use a call to getConnection() with a signa-
ture that includes the username and password as separate String parameters:
Search WWH ::




Custom Search