You are on page 1of 29

Unit 1 Enterprise Foundations Part B

Balasubba Raman Guruswamy

11 January 2011

Enterprise Computing Enterprise Foundations

Goal to represent business concepts to


Applications within the business An XML interface for vendors or clients Web interface for customers

Requirements Must have minimal proprietary components


Platform independent, database independent Able to integrate new technologies Internationalisation, Localsation, Accessibilty, Customisation

Must be capable of personlised experience

Must be authoritative, shared source for business concepts

Transparent to the user

Multi-tier typical application

Stand-alone client

Web-centric application

Business-to-business

JDBC JavaMail Java API for XML Parsing (JAXP) Web services APIs

JDBCTM technology is an API that lets you access virtually any tabular data source from the JavaTM programming language.

Cross-DBMS connectivity to a wide range of SQL databases Access to other tabular data sources, such as spreadsheets or flat files.

http://java.sun.com/products/jdbc/index.html

Java Application JDBC API Java Core APIs Application JDBC Driver Database Server

JVM
Database

Level 1 - A JDBC-ODBC bridge provides JDBC API access via one or more ODBC drivers.

Level 2 - A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Level 3 - A net-protocol fully Java technology-enabled driver translates JDBC API calls into a DBMSindependent net protocol which is then translated to a DBMS protocol by a server. Level 4 - A native-protocol fully Java technologyenabled driver converts JDBC technology calls into the network protocol used by DBMSs directly.
http://java.sun.com/products/jdbc/driverdesc.html

Type 1: ODBC Bridge

Java App

JDBC API

JDBC Bridge Driver

MS ODBC

Database Server

Database Type 2: Native DB API Java App JDBC API JDBC Driver Native API Library Native API Database

Type 3: Pure Java

Java App

JDBC API

JDBC Driver

Database Translator

Database Server

Database Type 4: Pure Java Direct

Java App

JDBC API

JDBC Driver

Database Server

Database

Basic sequence of operations for a program that will use JDBC to interact with a database:

Load the correct JDBC driver (using the classname) Open a Connection to the database (using a URL) Create statements (using the Connection) Execute statements and process results Close the Connection

JDBC always refers to databases by URLs.


General structure of a JDBC URL is:
jdbc:<subprotocol>:<dbname>[params]

Some common examples:


jdbc:odbc:aMSAccessDB jdbc:odbc:oDatabase2;UID=jeffsix;PWD=simplePW jdbc:mysql://dbserver/myDB?user=jeff&password=easy jdbc:postgresql://psServer.mycorp.com:1878/myDB jdbc:sequelink://host5/someDB;uid=bob;password=pop

There are many methods a program can call on its valid Connection object.
createStatement() method will create a Statement object that can be used to assemble and run SQL commands. preparedStatement() creates an object that is associated with a predefined SQL command (the Statement object can be used for arbitrary statements and can be reused for other SQL commands) getMetaData() method will return metadata associated with the database, including descriptions of all of the tables in the DB. prepareCall() method is used to call stored procedures in the SQL database.

There are many methods a program can call on its valid Statement object.
executeQuery() method executes a SQL query statement and returns the results (as a ResultSet) executeUpdate() method executes a SQL update (such as UPDATE, INSERT, or DELETE) execute() method executes other, more generic, SQL statements. setMaxRows() method allows the program to set the maximum number of data elements (rows) that can be returned from a query statement.

There are MANY more methods for both the Connection and Statement classes.

The most popular thing for a Java program to do via JDBC is to perform queries on a DB.

Perform a query using a Statement object and its executeQuery() method. This method will return a ResultSet object that gives you access to the query rows.
A ResultSet is just like a database table; it has zero or more rows (zero if no data elements match the query criteria) and each row has one or more columns

Performing a query and interacting with the ResultSet


ResultSet queryResults; theQueryResults = theStatement.executeQuery( "select distinct dept from instructors"); while(theQueryResults.next()) { System.out.println(Dept:" + queryResults.getInt(1)); } theQueryResults.close();

ResultSet objects keep track of their position internally, starting before the first row. You can use next() and other navigation methods to move through them

There are multiple methods of extracting data from the current row in a ResultSet.
getString() method returns the value of a particular column in the current row as a String. getInt() method returns the value of a particular column in the current row as an int. getBoolean() method returns the value of a particular column in the current row as an boolean. getDouble() method returns the value of a particular column in the current row as an double. getObject() method returns the value of a particular column in the current row as an Object.

Two versions of both of these methodsone takes the column as an integer index, one takes the columns name as a String.

There are three types of statement objects in JDBC programming:

Statement - allows the execution of arbitrary statements on the database. PreparedStatement - allows the program to execute the same SQL command repeatedly, while allowing substitutions for particular words or values (to make it more useful). CallableStatement - allows the program to execute SQL stored procedures, with substitutions for arguments. A stored procedure is a function that is part of, and stored inside, a SQL database (hence the name).

import java.sql.*; public class IDQuery { static String url = "jdbc:mysql://localhost/instructors"; public static void main(String [] args) { try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); Connection theConnection; PreparedStatement prep_statement; ResultSet theQueryResults; theConnection = DriverManager.getConnection(url,jeffsix,arrrr!); prep_statement = theConn.prepareStatement("SELECT name,dept FROM instructors WHERE ID=?"); for(int i = 0; i < args.length; rs.close(), i++) { prep_statement.setString(1, args[i]); theQueryResults = prep_statement.executeQuery(); if (theQueryResults.next()) System.out.println(theQueryResults.getString(1) + "," + theQueryResults.getString(2)); else System.out.println(Query + i + not found!); } prep_Statement.close(); theConnection.close(); } catch (Exception exp) { System.err.println("Execption! - " + exp); } }
}

CallableStatement calls a SQL stored procedure inside the DB. The stored procedure is specified upon object creation (using the Connections prepareCall() method). Syntax of this call is
? = call procedurename(?,?) } for a procedure that takes 2 arguments; returns a value { call procedurename(?,?,?,?) } for a procedure that takes 4 arguments; does not return a value The syntax is CallableStatement callable; callable = conn.prepareCall("{ call replace(?,?) }"); callable.setString(1, oldString); callable.setString(2, newString); int rows_modified = callable.executeUpdate();

Your program can create a Batch of statements (any of the three types) and execute that batch on the database all at once

The addBatch() method adds a statement to the current batch The executeBatch() method runs all of the statements in the batch on the database The clearBatch() method clears the statements from the batch without running them

As SQL defines its own datatypes, it is important to understand the mapping between SQL and Java datatypes
SQL Java --------------------BIT boolean BIGINT long BINARY byte[] CHAR String DATE Date DOUBLE double FLOAT float INTEGER int BLOB CLOB Blob Clob SQL Java ------------ ------------NUMERIC BigDecimal REAL float SMALLINT short TIME Time TIMESTAMP Timestamp TINYINT byte VARBINARY byte[] VARCHAR char[] REF STRUCT Ref Struct

SQLs offer two ways to support storage and retrieval of binary data in database tables:

Binary columns: BINARY / VARBINARY - these kinds of columns are suitable for small arrays of bytes (they are not very memory efficient). Binary large object columns: BLOB / LONGBLOB - these kinds of columns are suitable for large arrays of bytes, but are not supported in all database systems (they are much more memory efficient).
used to store image, audio, signal, or video data used to store serialized Java objects suitable for storing entire documents inside databases (as documents are really just binary data)

BLOBs are useful in many databases:

Storing binary data into the database

Using the SQL INSERT verb, the binary column is set using either the setObject() method and passing it a byte array or using the setBinaryStream() method and passing it an InputStream (which the JDBC driver will then use to fill in the columns data field)

Retrieve binary data from the database

Use a normal query, and either getObject() to return a byte array, getBlob() to return a Blob object, or getBinaryStream() to get an InputStream which can be used to read from this data field

JDBC is a core Java technology that supports access to relational databases and database servers.
JDBC uses the standard Structured Query Language (SQL) for all database interaction.

In order to use JDBC with a particular database, you must install a driver for the database server you are using and load that driver in your programs.
Almost all JDBC functionality is accomplished through the use of SQL statements, of three kinds Statement, PreparedStatement, and CallableStatement.

1.
2. 3. 4. 5. 6.

What are the goals and objectives of True Enterprise System ? What is JDBC? Give basic sequence of operations for a program using JDBC to interact with a database. What is ResultSet in JDC? How does JDBC refer to a database in a program code? Give the syntax. What are the three types of JDBC statement objects?

11 January 2011

Enterprise Computing Enterprise Foundations

28

1. 2.
3. 4.

Give details of different types of JDBC drivers. Give brief note on JDBC Connection Class and JDBC Statement Class. Describe the four methods of extracting data from current row n a ResultSet. Give s brief note on JDBCs support for binary data in dstabase tables.

11 January 2011

Enterprise Computing Enterprise Foundations

29

You might also like