[ Team LiB ] Previous Section Next Section

What Is JDBC?

Java Database Connectivity (JDBC) is an API that lets you access any tabular data sources from a Java application. These data sources can include SQL-based databases or data stored in spreadsheets or flat files. Most commercial databases, such as the ones listed earlier in this hour, now support JDBC by means of a JDBC driver. A Java application can use different JDBC drivers, all of which expose the same interface to the developers. This enables developers to plug different databases into their Java applications.

JDBC exposes an API that allows developers to connect to a database, execute SQL statements on the database, and manipulate any data that is returned as a result of the execution of a database statement. The JDBC driver manages all of this for a specific database and also supports the pooling of database resources such as the connections.

Using JDBC you can connect to a database. To do this, you would create a new JDBC connection using the following statements:


Class.forName("com.ibm.db2j.jdbc.DB2jDriver");
Connection con = DriverManager.getConnection(
    "jdbc:db2j:PeopleDB", username, password);

In the first statement, you are loading the appropriate driver class. In the second, you create the connection to the database by passing in the connection URL, which includes the driver name (db2j), the database name (PeopleDB), and the username and password for the database. The username and password are sometimes optional.

The next step is to create a statement that will contain the SQL that you want to execute on the database. This command looks like


Statement stmt = con.createStatement() ;

As soon as you have created the statement, you can execute the statement in different ways using appropriate SQL statements. You would create a string with this SQL statement:


String sqlString = "some sql code";

Now you can execute the SQL statement by using either of the following commands as appropriate:


stmt.executeUpdate(sqlString);

ResultSet rs = stmt.executeQuery(sqlString);

You would use the executeUpdate database in conjunction with an insert or update SQL statement. You would use the executeQuery statement in conjunction with a select SQL statement.

After using the results of your query, the final step is to release the connection:


con.close();

Learn More About JDBC

graphics/bytheway_icon.gif

To learn more about JDBC and the syntax and usage of the JDBC API, you can go to http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/index.html.


    [ Team LiB ] Previous Section Next Section