Accessing a Database

Example 18-1 shows a program that connects to a database and then loops, prompting the user for a SQL statement, sending that statement to the database, and displaying the results. It demonstrates the four most important techniques for JDBC programming: registering a database driver, using the DriverManager class to obtain a Connection object that represents a database connection, sending a SQL statement to the database using the Statement object, and retrieving the results of a query with a ResultSet object. Before we look at the specifics of the ExecuteSQL program, let’s examine these basic techniques.

One of the interesting things about the java.sql package is that its most important members—such as Connection, Statement, and ResultSet—are interfaces instead of classes. The whole point of JDBC is to hide the specifics of accessing particular kinds of database systems, and these interfaces make that possible. A JDBC driver is a set of classes that implement the interfaces for a particular database system; different database systems require different drivers. As an application programmer, you don’t have to worry about the implementation of these underlying classes. All you have to worry about is writing code that uses the methods defined by the various interfaces.

The DriverManager class is responsible for keeping track of all the JDBC drivers that are available on a system. So the first task of a JDBC program is to register an appropriate driver for ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.