|
15.2. Introducing JDBCFor many real-world applications, there are copious amounts of data associated with them. Programmers first learn to store data into files, but serious applications require a database. Java programs can connect to and query a database with the help of several Java classes which together make up the Java DataBase Connectivity API, or JDBC. With JDBC, your Java programs will be able to connect to databases anywhere on the network and to query data from the database with the simple syntax that database programmers have been using for yearsSQL. JDBC provides an abstraction, a way to talk about the various aspects of working with a database which is largely vendor-independent. Implementations of JDBC can be, and are, built for many different databases and even other data sources, such as flat files and spreadsheets. The Linux environment offers several choices of databases, the two most popular being MySQL and PostgreSQL. Both are Open Source projects available with most major Linux distributions, as well as online for downloading. For many Java and Linux developers, however, the use of Java and Linux will include their development environment and the servers to which they deploy their applications, but the database to which they connect will still be the corporate database. For most commercial applications this is an Oracle database, the industry leader, and due to its major presence in the marketplace we will use Oracle in our examples as well. Note JDBC interfaces are available for almost any commercial database with any significant marketshare. See Section 15.9 for a URL that has a list of such choices. Most of what you will learn in this chapter will apply regardless of the database you connect to. To make even the most basic use of JDBC, you must understand three basic operations:
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 samewhich is what you'd hope for in an abstraction. This is a good news for developers: "Learn once, use anywhere." |
|