Java Reference
In-Depth Information
that are easily separable from the core JDBC API, such as connection pooling and
rowsets, have been added to javax.sql. Putting these advanced facilities into an
optional package instead of into the JDBC 2.0 core API helps to keep the core JDBC
API small and focused.
The main strength of JDBC is that it is designed to work in exactly the same way with
any relational database. In other words, it isn't necessary to write one program to
access an Oracle database, another to access a Sybase database, another for SQL
Server, and so on. JDBC provides a uniform interface on top of a variety of different
database-connectivity modules. As you will see in Part II of this topic, a single
program written using JDBC can be used to create a SQL interface to virtually any
relational database. The three main functions of JDBC are as follows:
 
Establishing a connection with a database or other tabular data source
 
Sending SQL commands to the database
 
Processing the results
Listing 4-1 provides a simple example of the code required to access an Inventory
database containing a table called Stock, which contains the names, descriptions,
quantities, and costs of various items. The three steps required to use JDBC to
access data are clearly illustrated in the code.
Listing 4-1: Simple example of JDBC functionality
package java_databases.ch04;
import java.sql.*; // imports the JDBC core package
public class JdbcDemo{
public static void main(String args[]){
int qty;
float cost;
String name;
String desc;
// SQL Query string
String query = "SELECT Name,Description,Qty,Cost FROM Stock";
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // load the JDBC driver
Connection con = DriverManager.getConnection ("jdbc:odbc:Inventory");
// get a connection
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query); // execute query
while (rs.next()) { // parse the results
name = rs.getString("Name");
Search WWH ::




Custom Search