<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>unsaturated.com &#187; java</title>
	<atom:link href="http://www.unsaturated.com/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.unsaturated.com</link>
	<description>The personal and professional website of Matthew Crumley</description>
	<lastBuildDate>Mon, 19 Apr 2010 03:51:34 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Java Data Base Connectivity (JDBC)</title>
		<link>http://www.unsaturated.com/essays/jdbc/</link>
		<comments>http://www.unsaturated.com/essays/jdbc/#comments</comments>
		<pubDate>Mon, 16 Jul 2007 03:48:30 +0000</pubDate>
		<dc:creator>Matthew Crumley</dc:creator>
				<category><![CDATA[Essays]]></category>
		<category><![CDATA[college]]></category>
		<category><![CDATA[essay]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://www.unsaturated.com/essays/jdbc/</guid>
		<description><![CDATA[My undergraduate course on Communication Networks focused on the architecture of computer networks, their models, and protocols.  The class required a brief research paper, so I coauthored this paper on JDBC.]]></description>
			<content:encoded><![CDATA[<h3>1.0 INTRODUCTION</h3>
<p>Networking is the concept of sharing resources and services. A resource could be physical hardware or data, and a service could be an e-mail system. In other words, resources <em>are</em> things and services <em>do</em> things. The individual systems which are networked must be connected through a pathway (called the transmission medium) that is used to transmit the resource or service between the computers. All systems on the pathway must follow a set of common communication rules for data to arrive at its intended destination and for the sending and receiving systems to understand each other. The rules governing computer communication are called protocols.</p>
<p>Having a transmission pathway does not always guarantee communication. When two entities communicate they do not merely exchange information, rather, they must understand the information they receive from each other. The goal of computer networking, therefore, is not simply to exchange data but to understand and use data received from other entities on the network. Because computers can be used in different ways and can be located at different distances from each other, enabling computers to communicate often can be a daunting task that draws on a wide variety of technologies.</p>
<p>The two main reasons for using computer networks are to provide services and to reduce equipment costs. Networks enable computers to share their resources by offering services to other computers and users. Specific reasons for networking PCs include sharing files, printers and other devices, enabling centralized administration and security of the resources within the system, and supporting network applications such as e-mail and database services. Database servers are the most common type of application servers. Because database services enable applications to be designed in separate client and server components, such applications frequently are called client/server databases.</p>
<p>With a client/server database, the client and server applications are designed to take advantage of the specialized capabilities of client and database systems. The client application manages data input from the user, generation of screen displays, some of the reporting, and data retrieval requests sent to the database server. The database server manages the database files; adds, deletes, and modifies records in the database; queries the database and generates the results required by the client; and transmits results back to the client. The database server can service requests for multiple clients at the same time.</p>
<p>Database services relieve clients of most of the responsibilities for managing data. A modern database server is a sophisticated combination of software that can provide database security, optimize the performance of database operations, determine optimum locations for storing data without requiring clients to know where data is located, service large numbers of clients by reducing the amount of time any one client spends accessing the database, and distribute data across multiple database servers.</p>
<p>In the late 1990s the demand for database information shifted. Distributed databases became increasingly popular. Obtaining information from a proprietary source did not suffice. The demand for information came from a multitude of users using a myriad of networked PCs. The bottom line: all users want access to the data they want on every machine they use. Thus, the demand for database connectivity has also shifted.</p>
<h3>1.1  SQL BASICS</h3>
<p>Structured Query Language (SQL) is the standard language for accessing relational databases. SQL is not a typical programming language. It is used to define and manipulate data. The current ISO operating standard is SQL92<sup>1</sup>. Unfortunately, SQL is not yet as standard as one would like. One area of difficulty is that data types used by different Data Base Management Systems (DBMSs) sometimes vary and the variations can be significant. As more and more developers use SQL, extensions of grammar make it difficult when working with more than one database. Many times a database may conform to the standard but may not implement all the capabilities that it defines.</p>
<p>Execution of an SQL statement manipulates the data in the tables. The most commonly used SQL statements are CREATE TABLE, INSERT INTO, SELECT FROM, UPDATE and DELETE FROM. A relational database is made up of tables. To create a table, the command is CREATE TABLE; it is followed by the table name then the columns. Each field is defined by a data type and a length. The INSERT INTO command inserts columns into the table; this command is followed by the table name then parenthesis to enclose the columns that will be inserted. The actual values for the columns are inserted using the VALUES command. The SELECT FROM command specifies where to retrieve the data, which data to retrieve and how to see the data displayed; it also allows for narrowing the search using the WHERE and AND commands. The UPDATE command, as its name suggests, allows the table to be updated. The SET and WHERE commands allow the update of a specific column entry. The DELETE FROM command is used to delete a row in the table; it is also used with the WHERE command.</p>
<p>Another area of difficulty with SQL conformance is that most DBMSs use a standard form of SQL for basic functionality; however, they do not conform to the more recently defined standard SQL syntax or semantics for more advanced functionality. For example, not all databases support stored procedures or outer joins, and those that do support it are not always consistent with each other. Also, support for SQL3 features and data types varies greatly. It is hoped the portion of SQL that is truly standard will expand to include increased functionality.</p>
<h3>2.0 PROBLEM DESCRIPTION</h3>
<p>Since a great deal of industry applications are database-oriented and many are Web-enabled, there needed to be an API compatible across many platforms and machines. The common need for data access was pushing the industry away from vendors with proprietary systems.</p>
<p>Microsoft created the Open Data Base Connectivity (ODBC) standard for connecting to databases and—like many database-tool vendors—it uses SQL for accessing relational database systems. However, users demanding data were left with multiple databases and multiple means of accessing them via DBMSs.</p>
<p>What was needed was a way for users to communicate with a variety of different data sources. Based on Java&#8217;s acceptance (in business and academia) and its &#8220;write once, run anywhere&#8221; concept, Java was a natural means for database connectivity development. Thus, Java Data Base Connectivity (JDBC) was born.</p>
<p>JDBC was conceived in September 1995, proposed in January 1996, announced in March 1996, and finalized in May 1996. Sun Microsystems and industry leaders (Oracle, Sybase, Informix, Symantec, and Intersolv) had emerged with an answer to user&#8217;s database connectivity demands.</p>
<p>JDBC is very similar to Microsoft&#8217;s ODBC. They can both interface with SQL but the question lingers: why and how should JDBC be implemented as an SQL interface when a solution already exists?</p>
<h3>3.0 DESIGN SOLUTION</h3>
<p>Prior to the development of the JDBC API, Microsoft&#8217;s ODBC API was the most widely used programming interface for accessing relational databases, as it offers the ability to connect to almost all databases on almost all platforms. With the help of the JDBC-ODBC Bridge, it is possible to use ODBC from Java. JDBC API builds on ODBC rather than starting from scratch. Programmers familiar with ODBC find it very easy to learn. The major difference is that JDBC API builds on and reinforces the style and virtues of Java, and it goes beyond just sending SQL statements to a relational DBMS. When ODBC is used, the ODBC driver manager and drivers must be manually installed on every client machine. When the JDBC driver is written completely in Java, however, JDBC code is automatically installable, portable, and secure on all Java platforms from network computers to mainframes<sup>2</sup>.</p>
<h3>3.1 JDBC API</h3>
<p>The JDBC API is used to invoke SQL commands directly. It works very well in this capacity and is easier to use than other database connectivity APIs, but it was also designed to be a base for alternate interfaces and tools. It tries to use a more understandable or more convenient API that is translated behind the scenes into the JDBC API. So, it builds upon previous database connectivity and provides its own unique solution.</p>
<p>The JDBC package provides a simple solution: use Java to connect, query, and update a database using SQL. This is a relatively straightforward solution to database connectivity, but has many different implementations. Programs using the JDBC API communicate via a JDBC driver manager which uses a currently installed driver. The major classes and interfaces that the JDBC API provides are defined in <a href="/wordpress/wp-content/data/jdbc-table1.png" title="Table 1">Table 1</a><sup>1</sup>.</p>
<h4><em>3.1.1  DriverManager</em></h4>
<p>The DriverManager class implements the Driver interface. It is the class that manages the JDBC drivers. It is also responsible for the connection to the database that is accessed through the drivers. To specify a particular driver, you use the system property &#8220;jdbc.drivers&#8221;, the DriverManager will load the driver specified. You may set the property of the &#8220;jdbc.drivers&#8221; through the setProperty() method in the System class or in the Properties class The driver may also be loaded explicitly by using the forName() method in Class class. When the driver class is loaded, it automatically calls the DriverManager class method. The DriverManager class has methods for creating a connection to a JDBC driver. The objects are implement using Connection by using getConnection() method. The forName() method is called in the beginning of main() enabling it to throw an exception if the driver is not loaded for some reason. These classes and interfaces for the JDBC libraries are defined and imported from the java.sql package. Listed below are some examples of how these are used<sup>1</sup>.</p>
<pre class="code">
<code>// Sets the driver
System.setProperty ("jdbc.drivers", "sun.jdbc.odbc.JdbcOdbcDriver");

// Loads the ODBC driver
Class.forName("sun.jdbc.odbc.JdbcOdbc.Driver");

// Connection made using a URL string to specify the database location
Connect databaseConnection = DriverManager.getConnection(source);

// Connection to a database and sends the username and password
databaseConnection = DriverManager.getConnection(sourceURL, username, password);</code></pre>
<h4><em>3.1.2  Statement Objects</em></h4>
<p>Statement objects are of the class that implements the Statement interface. The Statements objects are created by using createStatement() method of a valid Connection object. To execute an SQL query, use the executeQuery()method. The contents of the query are passed as a string argument for the method. The Statement object also allows for batching queries, which may be executed at a later time. For batching, the methods are executeBatch() and clearBatch().</p>
<h4><em>3.1.3  ResultsSet Objects</em></h4>
<p>ResultsSet are of the class that implements the ResultSet interface. It returns the results of a table of the executed SQL query and contains a cursor. The cursor allows the manipulation of any row in the set. The cursor initially is pointing to a position that precedes the first row in the table. The cursor can be moved to the next position by using the next() method. The method will return a true if there is a next row. The methods first() and last() will position the cursor to the first or last row when called. In addition, the methods beforeFirst() and afterLast() move the cursor position the row before the first or after the last row. The previous() method moves the cursor to the previous row to where the cursor is currently positioned. As with the next() method, previous() will also return true if there is a previous row and false if there are not any additional rows. To verify whether the cursor is positioned at the beginning or end of the table, call the isLast() or isFirst() methods. To see the results for all rows, a while loop is used as seen in the example below.</p>
<pre class="code">
<code>while(resultset.next())
{
  //your code for processing the rows
}</code></pre>
<p>ResultSet has predefined methods for retrieving information about columns in the query table. These methods are listed in <a href="/wordpress/wp-content/data/jdbc-table2.png" title="Table 2">Table 2</a><sup>1</sup>.</p>
<p>The JDBC API provides a ReultSetMetaData object that lets you peek into the data behind the ResultSet object. A few of the methods for the ResultSetMetaData are listed in <a href="/wordpress/wp-content/data/jdbc-table3.png" title="Table 3">Table 3</a><sup>1</sup>.</p>
<h3>3.2  JDBC ARCHITECTURE</h3>
<p>There are two JDBC architectures used to talk with the database. The first uses the JDBC driver to communicate directly with the database. The second uses a &#8220;bridge&#8221; to communicate with an ODBC driver<sup>3</sup>. The bridge structure was created to take advantage of the large number of ODBC-enabled data foundations. When using a bridge, there are more operations necessary to use a JDBC driver, opposed to the former architecture.</p>
<p>The two architectures have pros and cons. Solutions using JDBC have varying tiers of integration with ODBC and SQL. One area of difficulty is that data types used by different DBMSs sometimes vary, and the variations can be significant. JDBC deals with this by defining a set of generic SQL type identifiers in the class java.sql.Types. It&#8217;s worthy to note that the JDBC API can be used in both applets and stand-alone applications. This opens the door for many different implementations, as stated earlier. There are more than 20 commercially available JDBC implementations for users to choose from<sup>4</sup>. However, the selected implementation should be determined by the application&#8217;s requirements.</p>
<p>To encompass all these implementations, it is easier to segment them based upon two-tier and three-tier models. These two models can then be used to implement four different technical approaches—also, by no coincidence, four different types of drivers.</p>
<p>The two-tier model emerged with the coming of server technology. The database developer could create a front-end application that opened data through a connection to the back-end server. In this model the Java applet (or application) can talk directly to the database. The JDBC driver manager can open the database via a JDBC driver and then use the connection to make calls to queries and fetch results directly with the JDBC driver. The three-tier model is similar with one exception: there&#8217;s middleware.</p>
<p>The middleware is the actual service, which sends SQL statements to the database. The database returns with data to the &#8220;middle tier&#8221; and then on to the user. The client talks to the intermediate server that provides an abstract layer from the RDBMS. The models are sound and have been implemented in four different driver types to connect with individual databases. Those drivers come in four varieties. Types 1 and 2 are intended for programmers writing applications, while Types 3 and 4 are typically used by vendors of middleware or databases.</p>
<h4><em>3.2.1  Type I Driver: JDBC-ODBC Bridge</em></h4>
<p>Its main purpose is to take advantage of the myriads of ODBC-enabled data sources widely used by developers to connect to databases in a non-Java environment. This is a good approach for learning JDBC. Also, it may be useful for companies that already have ODBC drivers installed on each client machine—typically the case for Windows-based machines running productivity applications. Finally, it may be the only way to gain access to some low-end desktop databases. The solution allows access to databases from multiple vendors. The stipulations are that the appropriate ODBC driver is chosen and that native code is preinstalled on any client that directly uses the bridge to implement the API calls (see Figure 1). The later is a major hindrance when considering clientprogram development. Some of the disadvantages to using this type include: this type is not for large-scale applications; performance suffers because there is some overhead associated with the translation work to go from JDBC to ODBC; it doesn&#8217;t support all the features of Java; the user is limited by the functionality of the underlying ODBC driver. The solution would be better implemented if pre-installing is eliminated. The next driver type attempts a similar implementation but has similar caveats.</p>
<p><img src="/wordpress/wp-content/data/jdbc-figure1.png" alt="Figure 1" id="centered" /><br />
<center><small>Figure 1 (Left to Right) Type I and Type II drivers</small></center></p>
<h4><em>3.2.2  Type II Driver: The native-API, partly Java Driver</em></h4>
<p>This is also two-tier, in that the JDBC driver requires a vendor-supplied library to translate JDBC functions into the DBMS&#8217;s query language<sup>4</sup>. These drivers, much like the JDBC/ODBC bridge, require preinstalled software installed on the client&#8217;s computer. This type converts the calls that a developer writes to the JDBC application programming interface into calls that connect to the client machine&#8217;s application programming interface for a specific database, such as IBM, Informix, Oracle or Sybase. The performance is better than that of Type 1, in part due to eliminating the extra ODBC translation layer (see Figure 1). The fundamentals are very similar to the previous driver. The Type 2 driver contains compiled code that is optimized for the back-end database server&#8217;s operating system<sup>6</sup>. Disadvantages associated with this Type include: the user needs to make sure the JDBC driver of the database vendor is loaded onto each client machine; it must have compiled code for every operating system that the application will run on; the best use is for controlled environments, such as an intranet. The multi-tier (or three-tier) model presented next adds another layer to the database connectivity structure but comes closer to JDBC&#8217;s main goal of access anywhere, anytime, data.</p>
<h4><em>3.2.3  Type III Driver: The network-protocol, all-Java driver</em></h4>
<p>This pure Java driver for database middleware provides connectivity to many different databases. The driver translates JDBC calls into a database-independent network protocol, and is then translated to database-specific API calls by a middle-tier (middleware) server. The term middleware is acceptable because the middle-tier server can be a Type 1 or Type 2 driver<sup>4</sup>. The middleware can also be a native component or written in Java. The structure is three-tier because there is the JDBC client driver, middleware, and the database being accessed (see Figure 2). Type 3 provides better performance than Types 1 and 2. It can be used when a company has multiple databases and wants to use a single JDBC driver to connect to all of them. As it is server-based there is no need for JDBC driver code on the client machine. For performance reasons, the back-end server component is optimized for the operating system that the database is running on. This type incorporates security, firewalls, and proxies—issues very important to a multi-user (highly scalable) environment.</p>
<p>Insofar as configuration, the Type 3 driver has more server-side than client-side issues related to setup. The server must be configured for the database(s) being accessed—involving ports, environment variables and database-specific issues. The middleware could also be proprietary. All these issues point to the final driver type, which attempts to make connectivity seamless to the client. This Type needs some database-specific code on the middleware server. If the middleware must run on different platforms, a Type 4 driver might be more effective.</p>
<p><img src="/wordpress/wp-content/data/jdbc-figure2.png" alt="Figure 2" id="centered" /><br />
<center><small>Figure 2 (Left to Right) Type III and Type IV drivers</small></center></p>
<h4><em>3.2.4  Type IV Driver: Native-protocol, all-Java Driver</em></h4>
<p>This Type takes JDBC calls and converts them into packets that are sent over the network in the proprietary format used by the specific database. It allows a direct call from the client machine to the database. The driver can be written completely in Java (see Figure 2). This Type also provides better performance than Types 1 and 2, and there is no need to install special software on the client or server; it can be downloaded dynamically. This solution is accomplished without an ODBC or native API. These drivers are only available through the DBMS vendors because a high degree of protocol-specific knowledge is required to code the driver. The Java applets with JDBC driver can be downloaded to a browser without any client software installation<sup>7</sup>.</p>
<p>Using JDBC has become simpler for companies that opt to use an application server, which is software that sits between the client and the database server accepting and directing the data requests. Application servers have JDBC support built into them, reducing the amount of code the programmer needs to write.</p>
<p>Chad Ruff, president of Sage Software Inc. in Atlanta, who has been writing Java applications for three years said, &#8220;I can&#8217;t even imagine how much more productive I am with an application server rather than JDBC—maybe in the range of 400%.&#8221;</p>
<p>Daryl Plummer, an analyst at Stamford, Conn.-based Gartner Group Inc. predicts that by the end of 2001, when using an application server will be the dominant means of building new applications, &#8220;people will become much less concerned about JDBC drivers because they&#8217;ll have picked the application server because of its support for a certain database.&#8221;</p>
<p>JDBC can be helpful in at least the following three common business scenarios, according to Sun product manager Milena Volkova<sup>5</sup>.</p>
<ul>
<li>When there&#8217;s a need to disseminate information internally in a large company where departments have standardized on different platforms.</li>
<li>If a corporation has undergone a merger and finds itself with different operating systems and databases.</li>
<li>For e-commerce applications that run over the Internet, where the company has no control over the software its customers use. The customers only need the appropriate Java technology, which can be downloaded on the fly to their computers.</li>
</ul>
<p>Extending the solution domain of JDBC seems very straightforward according to Volkova&#8217;s scenarios. With two architecture models and four different driver types, the solutions available for connecting users to the data they want can be quite flexible. However, the reach of JDBC can better be shown through an example or case study.</p>
<h3>4.0 EXAMPLE</h3>
<p>An Oracle database was created called <em>jdbcstudents</em>. The database contains columns for first name, last name, email and grade. Three students were entered. A Java program was written to select the columns from the database <em>jdbcstudents</em> and display the results. The Java program uses the Type 2 driver, which has vendor specific class libraries. Although a database was created prior to the Java program, with some modifications to the code, the program is capable of creating a database directly.</p>
<pre class="code">
<code>import java.sql.*;
import java.util.*;
import java.io.*;

class jdbc
{
  public static void main( String args[]) throws SQLException
  {
    String databaseurl = "jdbc:oracle:" + "server.engr.ucf.edu";
    try{
      Class.forName ("oracle.jdbc.OracleDriver");
    }
    catch (ClassNotFoundException e)
    {
      System.out.println ("The driver could not be loaded");
      e.printStackTrace ();
    }
    Connection conn = DriverManager.getConnection(databaseurl , "user" ,"pass");
    System.out.println( "Attempting to connection to " + databaseurl);
    Statement stmt = conn.createStatement();
    System.out.println( "The connection has been made.");
    System.out.println( "Accessing the jdbcstudents database:n");
    System.out.println( "Firstnamet" + "Lastnamet" + "Emailt" + "Graden");
    ResultSet rset = stmt.executeQuery( "select firstname,
      lastname,
      grade,
      email from jdbcstudents");
    while( rset.next() )
    {
      System.out.println( rset.getString("firstname")
        + rset.getString("lastname")
        + rset.getString("email")
        + rset.getString("grade"));
    }
    rset.close();
    stmt.close();
    conn.close();
  }
}</code></pre>
<h3>5.0 CONCLUSION</h3>
<p>The novelty of JDBC leverages the pervasiveness of Java and its &#8220;write once, run anywhere&#8221; concept. However, JDBC is not the new paradigm of database connectivity nor is it a silver-bullet for giving users all the data they want, wherever they are located. The hardships in using JDBC are still apparent in the various driver types outlined: the burden is merely shifted from one side of the network to another. Some solutions require the user to install software, others do not.</p>
<p>A JDBC driver is a class that implements the JDBC Driver interface and understands how to convert program (and typically SQL) requests for a particular database. Clearly, the driver is what makes it all work. There are four different driver types, which are discussed in the design solution. The example application uses a Type 2 driver. Another driver type may make more sense for a particular project. Most database vendors now provide drivers to implement the JDBC API for their particular systems. These are generally provided free of charge.</p>
<p>The first job of the JDBC driver is to connect to the database, which means specific information must be passed to it. The basic information requirements are a Database URL (Universal Resource Locator), a user ID, and a password. Depending on the driver, there may be many other arguments, attributes, or properties available. The next job is to create a table. While the database contains tables, the tables are the actual components that contain data, in the form of rows and columns. The DDL CREATE TABLE statement accomplishes table creation. This statement has many options, some differing from vendor to vendor; the DBMS SQL reference will supply specifics.</p>
<p>Data can be entered and maintained using database-specific tools, or with SQL statements sent programmatically. We focused on using JDBC to send SQL statements to the database. After sending SQL commands to retrieve the data and using JDBC to get results into variables, program code works as with any other variables to display or manipulate that data.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.unsaturated.com/essays/jdbc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
