Sunteți pe pagina 1din 15

Java Database Connectivity

JDBC
JDBC is a Java Database Connectivity API that lets you access virtually any tabular data source from a Java application. JDBC defines a low-level API designed to support basic SQL functionality independently of any specific SQL implementation. 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. 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

Example of JDBC functionality 1/2


The example illustrates the following main steps required to access a database and retrieve data from a ResultSet using the JDBC API: Load a JDBC driver.
This example uses the JDBC.ODBC bridge plus ODBC driver

Get a connection to the database. Create a statement. Execute a SQL query. Retrieve data from the ResultSet.

import java.sql.*; // imports the JDBC core package public class JdbcDemo{ public static void main(String args[]){ int qty; float cost; String lastName, firstName; // SQL Query string String query = "SELECT LastName,FirstName FROM Employees"; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // load the JDBC driver Connection con = DriverManager.getConnection ("jdbc:odbc:MyDataBase"); // get a connection Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query); // execute query

Example of JDBC functionality 2/2


while (rs.next()) { // parse the results firstName = rs.getString("FirstName"); lastName = rs.getString("LastName"); System.out.println(firstName+ " "+ lastName); } con.close(); } catch(ClassNotFoundException e){ e.printStackTrace(); } catch(SQLException e){ e.printStackTrace(); } } }

ODBC
Short for Open DataBase Connectivity, a standard database access method developed by the SQL Access group in 1992. The goal of ODBC is to make it possible to access any data from any application, regardless of which database management system (DBMS) is handling the data. ODBC manages this by inserting a middle layer, called a database driver , between an application and the DBMS. The purpose of this layer is to translate the application's data queries into commands that the DBMS understands. For this to work, both the application and the DBMS must be ODBCcompliant -- that is, the application must be capable of issuing ODBC commands and the DBMS must be capable of responding to them.

JDBC-ODBC Bridge 1/2 Type 1: JDBC-ODBC bridge plus ODBC driver


The JDBC-ODBC bridge product provides JDBC access via ODBC drivers. ODBC (Open Database Connectivity) predates JDBC and is widely used to connect to databases in a non-Java environment. ODBC is probably the most widely available programming interface for accessing relational databases. The main advantages of the JDBC-ODBC bridge are as follows:
It offers the ability to connect to almost all databases on almost all platforms. It may be the only way to gain access to some low-end desktop databases and applications.

Its primary disadvantages are as follows:


ODBC drivers for a specific DMBS must also be loaded on the target machine. Translation between JDBC and ODBC affects performance.

JDBC-ODBC bridge 2/2


application (Visual Basic, Excel, Access)
data querie

SQL queries to access data

Java application
method call

Core ODBC library of functions, independent of application and db drivers


commands

functions call

JDBC-ODBC bridge +

DBMSs Microsoft Access Driver (*.mdb) Microsoft FoxPro Driver (*.dbf) Microsoft Excel Driver (*.xls) Relational or non-relational data sources (databases, spreadsheets, XML files)

DMBS driver must be loaded on target machine

The Database is represented by a DNS (Data Source Name)

Control panel>Administrative tools>DataSources(ODBC)

Two-Tier and Three-Tier Models 1/2


Two-Tier Model In the two-tier model, a Java application interacts directly with the database. Functionality is divided into these two layers: Application layer, including the JDBC driver, business logic, and user interface Database layer, including the RDBMS database is located on another machine, referred to as the server. application runs on the client machine The interface to the database is handled by a JDBC driver appropriate to the particular database management system being accessed. The JDBC driver passes SQL statements to the database and returns the results of those statements to the application.

Two-tier client/server configuration

Two-Tier and Three-Tier Models 2/2


Three-tier Model The main components of a three-tier architecture are as follows: Client tier, typically a thin presentation layer that may be implemented using a Web browser Middle tier, which handles the business logic or application logic. This may be implemented using a servlet engine such as Tomcat or an application server such as JBOSS. The JDBC driveralso resides in this layer. Data-source layer, including the RDBMS; runs on a dedicated database server. Functionality: commands are sent from client to an application server, forming the middle tier. application server then sends SQL statements to the database. database processes the SQL statements and sends the results back to the application server, Three-tier model typical of Web applications application server then sends them to the client. Advantages of three-tier architecture: Performance can be improved by separating the application server and database server. Business logic is clearly separated from the database. Client applications can use a simple protocol such as CGI to access services.

Prepared Statement
import java.sql.*; public class PreparedStmt{ public static void main(String args[]){ String name, title, city; String[] cities={"London","Seattle"}; String query = ("SELECT * FROM Employees WHERE City = ?"); try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Names and titles of Connection con = employees from the DriverManager.getConnection ("jdbc:odbc:MyDataBase"); PreparedStatement pstmt = con.prepareStatement(query); table Employees, for (int i=0; i<2;i++){ grouped on city pstmt.setString(1, cities[i]); ResultSet rs = pstmt.executeQuery(); System.out.println(cities[i]); while (rs.next()) { name = rs.getString("FirstName")+" "+rs.getString("LastName"); title = rs.getString("Title"); System.out.println(name+"\t"+title); } } } catch(ClassNotFoundException e){ e.printStackTrace(); } catch(SQLException e){ e.printStackTrace(); } } }

Scrollable Result Sets 1/2


Parses the Employees table in the revere order of rows import java.sql.*; // imports the JDBC core package public class ScrollableResultSet{ public static void main(String args[]){ int qty; float cost; String lastName, firstName; // SQL Query string String query = "SELECT LastName,FirstName FROM Employees"; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // load the JDBC driver Connection con = DriverManager.getConnection ("jdbc:odbc:MyDataBase"); // get a connection Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery(query); // execute query rs.afterLast(); //cursor after last line of the table

Scrollable Result Sets 2/2


while (rs.previous()) { // parse the results in reverse order firstName = rs.getString("FirstName"); lastName = rs.getString("LastName"); System.out.println(firstName+ " "+ lastName); } con.close(); } catch(ClassNotFoundException e){ e.printStackTrace(); } catch(SQLException e){ e.printStackTrace(); } } }

Updatable Result Sets


import java.sql.*; // imports the JDBC core package public class UpdatableResultSet{ public static void main(String args[]){ int qty; float cost; String lastName, firstName; // SQL Query string String query = "SELECT * FROM Employees"; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // load the JDBC driver Connection con = DriverManager.getConnection ("jdbc:odbc:MyDataBase"); // get a connection Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = stmt.executeQuery(query); ResultSetMetaData md = rs.getMetaData(); if(rs.getConcurrency()==ResultSet.CONCUR_UPDATABLE) System.out.println("UPDATABLE"); else System.out.println("READ_ONLY"); int nColumns = md.getColumnCount(); System.out.println("employees has" + nColumns +"columns"); for(int i=1;i<=nColumns;i++){ System.out.print(md.getColumnLabel(i)+((i==nColumns)?"\n":"\t")); } while (rs.next()) {

Updatable Result Sets

rs.updateString("City", "London"); rs.updateRow(); for(int i=1;i<=nColumns;i++){ System.out.print(rs.getString(i)+((i==nColumns)?"\n":"\t")); } } } catch(ClassNotFoundException e){ e.printStackTrace(); } catch(SQLException e){ e.printStackTrace(); } } }

Bibliography
John ODonahue: Java Database Programming Bible, Wiley, 2002

S-ar putea să vă placă și