Download lecture notes

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
ADVANCED POGRAMMING
(JAVA) COURSE
Topics:
 Java Database Connectivity (JDBC)
 Graphics Programming with Java 2D and
Java 3D
 Security
 Servlets
 Java Server Pages
 Java-Based Wireless Applications
Part I
Java Database
Connectivity
(JDBC)
Java Database Connectivity (JDBC)
A common programming interface writing
programs
that access information stored in
 databases,
spreadsheets, and
other data sources
either directly or through
middleware
JDBC cont’d
 By using the JDBC interface,
Java programmers can request a connection with a
database,
 Send query statements using SQL
Receive the results for processing.
 Java runs on many different hardware
platforms and operating systems,
 Developers can use JDBC to write applications
 access data across incompatible database
management systems running on varied platforms.
Internet Resources for JDBC
http://java.sun.com/docs/books/tutorial/jdbc/index.html
www.sql.org
industry.java.sun.com/products/jdbc/drivers
http://servlet.java.sun.com/products/jdbc/drivers
java.sun.com/products/jdbc/faq.html
http://java.sun.com/products/jdbc/articles/package2.html
http://java.sun.com/developer/Books/JDBCTutorial/chapter5.html
www.jguru.com/jguru/faq/faqpage.jsp?name=JDBC
What is the JDBC API?
 A set of classes and interfaces written in the Java
a standard API for tool/database developers &
makes possible to write database applications using an Java
API.
 Obtaining a variety of different data sources is
possible for Java applications
 Makes possible to publish a web page containing
an applet that uses information obtained from a
remote data source. For example:
To connect all employees (even if they are using Windows,
Macintosh, and UNIX machines) is possible as one or more
internal databases via an intranet
The JDBC 3.0 API
Includes two packages:

java.sql package

javax.sql package (adds server-side capabilities)
While downloading the Java 2 Platform
Standard Edition, Version 1.4 (J2SE), we can
automatically get both packages

The JDBC-ODBC Bridge provides a limited subset of the
JDBC 3.0 API.

Summary of new features has to be read at
http://www-106.ibm.com/developerworks/java/library/j-jdbcnew/
.
The java.sql Package
The java.sql Package
 Contains the entire JDBC API that sends SQL statements to
relational databases and retrieves the results of executing
those SQL statements.
 The Driver interface represents a specific JDBC implementation
for a particular database system.
 Connection represents a connection to a database.
 The Statement, PreparedStatement, and CallableStatement
interfaces support the execution of various kinds of SQL
statements.
 ResultSet is a set of results returned by the database in
response to a SQL query.
 The ResultSetMetaData interface provides metadata about a
result set
 DatabaseMetaData provides metadata about the database as a
whole.
Array
 Provides an interface to SQL ARRAY objects.
 getArray() method returns a standard Java array of
objects of the type returned by getBaseType().
 The contents of the array can also be returned as a
ResultSet using the various getResultSet() methods.
public abstract interface Array {
// Public Instance Methods
public abstract Object getArray () throws SQLException;
public abstract int getBaseType () throws SQLException
public abstract String getBaseTypeName () throws
SQLException;
public abstract ResultSet getResultSet () throws
SQLException; }
import java.sql. Connection;
import java.sql. DriverManager;
import java.sql. SQLException;
public class JdbcExam {
public static void main (String args[]) {
Connection con = null;
try {
Class.forName ("com.mysql.jdbc.Driver"). newInstance();
con =DriverManager. getConnection ("jdbc:mysql:///test", "root",
"secret");
if (!con.isClosed())
System.out.println ("Successfully connected to MySQL server
using TCP/IP...");
} catch(Exception e) {
System.err.println ("Exception: " + e.getMessage());
} finally {
try {
if(con != null)
con.close();
} catch (SQLException e) {}
}} }
import java.sql. Connection;
import java.sql. DriverManager;
import java.sql. SQLException;
we imported 3 classes from java.sql package.
 Connection represents a connection to a
database
 DriverManager manages JDBC drivers
used to create connections to databases
 SQLException is an exception class
which gets thrown in case any error occurs in the program
 We declare a local variable to hold our
java.sql. Connection object that we'll retrieve
from java.sql. DriverManager later on.
Connection con = null;
 We encapsulate our JDBC code in a
try/catch/finally block.
 This is to ensure that if any runtime error gets
thrown we catch it and display it to the user.
try { ... …
} catch(Exception e)
{
System.err.println("Exception: " + e.getMessage());
} finally { ... ….
}
 We take the first step in establishing a connection to
our MySQL database by loading the driver explicitly
using Class.forName() method
Class.forName("com.mysql.jdbc.Driver").newInstance();
 Once the JDBC driver has been loaded in the JVM,
we retrieve a connection to our MySQL database
running on the local system using
DriverManager.getConnection() method
 .The first argument to this method is complete
database URL, next parameter is the user name and
last parameter is the password.
con=DriverManager.getConnection("jdbc:mysql:///
test", "root", "secret");
 After these steps are completed, it is required to obtain a
connection to the MySQL database.
 We check to make sure we are properly connected and
display a success message if we are.
if(!con.isClosed())
System.out.println("Successfully connected to " +
"MySQL server using TCP/IP...");
 To close the connection, we execute the
Connection.close() method in the finally block of our
try/catch/finally statement.
try {
if(con != null)
con.close(); }
catch (SQLException e) {}
 The Connection.close() method can also throw
SQLException
 so that is why we encapsulate this close() method in a separate try/catch
block.
http://www.mysql.com/get/Downloads/MySQL4.0/mysql-4.0.18-win.zip/from/pick#mirrors
is the website which you can download the mysql
http://www.mysql.com/doc/en/Windows_installatio
n.html
is the website which you can install the mysql
javax.sql package
The javax.sql package
 Contains the JDBC 2.0 Standard Extension API.
 The classes and interfaces in this package provide new
functionality,
 connection pooling, that do not fall under the scope of the original JDBC API and
can therefore be safely packaged separately.
 The DataSource interface serves as a factory for Connection
objects;
 DataSource objects can be registered with a JNDI ( Java
Naming and Directory Interface )server, making it possible to
get the name of a database from a name service.
 PooledConnection supports connection pooling, which allows
an application to handle multiple database connections in a
fairly transparent manner.
 RowSet extends the ResultSet interface to a JavaBeans
component that can be manipulated at design time and used
with non-SQL data sources
What Is the JDBC-ODBC Bridge?
 A JDBC driver
implements JDBC operations which translate them into
ODBC operations.
 ODBC acts as a normal application program.
 The bridge implements JDBC for any database for
which an ODBC driver is available.
 contains a native library used to access ODBC.
 The Bridge is installed automatically with the Java 2
SDK, Standard Edition, as package sun.jdbc.odbc
.
A Base for Other APIs
 Java APIs are implemented as Java classes.
 The following are just a few of the available APIs except
JDBC
 Java Real Time
 Java Foundation Classes (JFC)
 Swing—user interface
 Remote Method Invocation (RMI)
 Java for XML (JAXP)
 Java for XML Messaging (JAXM)
 Java Sound
 Java Media Framework
 Java 2D and 3D graphics
 Java Naming and Directory Interface (JNDI)
http://www.alumni.caltech.edu/~croft/research/java/snapshot/
What Does the JDBC API Do?
 Establish a connection with a data source
 Send queries and update statements to the data source
 Process the results
Connection con = DriverManager.getConnection(
"jdbc:myDriver:wombat", "myLogin", "myPassword");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery ("SELECT a, b, c FROM
Table1");
while (rs. next()) {
int x = rs.getInt ("a")
String s = rs.getString ("b");
float f = rs.getFloat ("c");
}
Why not Use ODBC from Java?
 Before the development of the JDBC API
The most widely used programming interface Microsoft's ODBC
(Open DataBase Connectivity) API
 To access relational databases
 ODBC can be used with Java, but
 The best application is JDBC API
Applied as the form of the JDBC-ODBC Bridge
 ODBC is not appropriate for direct use from the Java
programming language
Uses C interface.
Occurs a number of drawbacks in the security, implementation,
robustness, automatic portability
 during the calls from Java to native C code
QUESTION:
What are other important differences between JDBC API and ODBC API?
 Once ODBC (as native code) is called, Java programming language can't
guarantee that a security violation won't occur (untrusted).
The Bridge’s usage
 A JDBC connection is opened
 using a URL with the odbc subprotocol.
 Loading is done as follows:
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
 Before any connection, the bridge driver class,
sun.jdbc.odbc.JdbcOdbcDriver
 added to the java.lang.System property named jdbc.drivers
OR
explicitly loaded using the Java class loader.
 After loaded, the ODBC driver creates an
instance of itself and registers this with the
JDBC driver manager.
What Is the JDBC URL Supported by
the Bridge?
uses the odbc subprotocol
jdbc:odbc:<data-source-name>[;<attribute-name>=<attribute-value>]*
jdbc:odbc:sybase
jdbc:odbc:mydb;UID=me; PWD=secret
jdbc:odbc:ora123; Cachesize =300
JDBC Drivers
 Provides JDBC access via one or more Open Database
Connectivity (ODBC) drivers.
 ODBC, which predates JDBC, is widely used by developers to
connect to databases in a non-Java environment.
 JDBC supports four categories of drivers:
JDBC- to ODBC driver (Type 1)
Native-API, partly driver (Type 2)
JDBC- Net pure driver (Part 3)
Native-Protocol pure Java driver (Type 4)
JDBC- to ODBC driver (Type 1)
 A good approach for learning JDBC. May be useful
for companies that already have ODBC drivers
installed on each client machine
 The case for Windows-based machines running productivity
applications.
 May be the only way to gain access to some low-end desktop
databases.
 Not for large-scale applications. Performance
suffers because there's some overhead associated
with the translation work to go from JDBC to
ODBC. Doesn't support all the features of Java.
User is limited by the functionality of the underlying
ODBC driver
Native-API, partly driver (Type 2)
 Converts the calls that a developer writes to the JDBC
application programming interface into calls that
connect to the client machine's application
programming interface for a specific database, such
as IBM, Informix, Oracle or Sybase.
 Performance is better than that of Type 1, in part
because the Type 2 driver contains compiled code
that's optimized for the back-end database server's
operating system.
 User needs to make sure the JDBC driver of the
database vendor is loaded onto each client machine.
Must have compiled code for every operating system
that the application will run on. Best use is for
controlled environments, such as an intranet.
JDBC- Net pure driver (Type 3)
 Pure Java driver for database middleware, which provides connectivity to
many different databases.
 Translates JDBC calls into the middleware vendor's protocol, which is then
converted to a database-specific protocol by the middleware server
software.
 Better performance than Types 1 and 2. Can be used when a company has
multiple databases and wants to use a single JDBC driver to connect to all
of them.
 Server-based, so no need for JDBC driver code on client machine.
 For performance reasons, the back-end server component is optimized for
the operating system that the database is running on.
 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.
Native-Protocol pure (all) Java driver
(Type 4)
 Written entirely in Java
 Converts JDBC calls into packets
that are sent over the network in the proprietary format
used by the specific database.
 Allows a direct call from the client machine to the database.
 Better performance than Types 1 and 2.
 No need to install special software on client or server. Can be
downloaded dynamically.
.
Type 4 Java Driver
cont’d
 Not optimized for server operating system, so the
driver can't take advantage of operating system
features.
The driver is optimized for the database and can take advantage
of the database vendor's functionality.
User needs a different driver for each different database
 These drivers are also well suited for applet
programming, provided that the Java security
manager allows TCP/IP connections to the
database server.
Driver Types Results
 Type 1 and Type 2 drivers were provided primarily
to allow Java programmers to create data-driven
solutions before database vendors created pure
java drivers
 Type 3 and Type 4 drivers are preferred, because
they are pure Java solutions
The cloudscape driver
COM.cloudscape.core. RMiJdbcDriver
is a Type 4 driver
New APIs from Microsoft




OLE (Object Linking and Embedding) DB
ADO (ActiveX Data Objects)
RDS (Remote Data Service)
UDA (Universal Data Access)
an umbrella term that covers OLE DB, ADO, RDS, and
ODBC
 The JDBC 2.0 API contains all of the important
functionality of UDA plus features not found in UDA, such
as SQL3 support.
OLE DB
 Microsoft's strategic low-level application program
interface
 for access to different data sources.
 Includes the SQL capabilities of the Microsoftsponsored standard data interface Open Database
Connectivity
 Includes access to data other than SQL data.
 As a design from Microsoft's Component Object
Model (COM), OLE DB is a set of methods, for
reading and writing data.
 The objects in OLE DB consist mainly of a data
source object, a session object, a command object,
and a row set object. :
An application using OLE DB

Initialize OLE

Connect to a data source

Issue a command

Process the results

Release the data source object

Uninitialize OLE
As a result:

A general-purpose set of interfaces designed to let
developers build data access tools as components
using the Component Object Model (COM).

OLE DB enables applications to have uniform access to
data stored in DBMS and non-DBMS information
containers

OLE DB takes advantage of the benefits of database
technology without having to transfer data from its place of
origin to a DBMS
ActiveX Data Objects (ADO)
 A language-independent object model
Expose data by an OLE DB Provider.
 The most commonly used OLE DB Provider
the OLE DB Provider for ODBC Drivers,
 Exposes ODBC Data sources to ADO.
 ADO is newer and more like the JDBC API
 it is not pure Java
http://msdn.microsoft.com/library/default.asp?url=/downl
oads/list/dataaccess.asp
Remote Data Service (RDS)
 The part of Microsoft's ActiveX Data Objects (ADO)
programming model designed for remote data access in
internet client/server applications.
 On both client and server computers it depends upon the
installation of the Microsoft Data Access Components
(MDAC).
 RDS has three core objects that are used to retrieve,
manipulate, and update data in applications.
Remote Data Service (RDS) con’t
 The RDS.DataControl and
RDS.DataSpace objects
installed on client computers and are directly
accessed within applications to retrieve data from
servers
 The RDSServer.DataFactory object, a
server component
can be accessed directly to communicate with
data sources
operates behind the scenes with the other RDS
objects in handling database maintenance
Cloudscape
• Cloudscape is a DBMS, a database management system,
accessed by applications through the JDBC API.
 IBM Cloudscape provides developers a small footprint,
standards- based Java database that can be tightly embedded
into any Java based solution.
 Supports complex SQL, transactions and JDBC so that your
applications can be migrated to DB2 UDB when they need to
grow.
 Supports data encryption on disk via JCE for secure operation
in hostile environments.
http://www.deitel.com/books/advjHTP1/advjHTP1_CloudscapeInst
allation.html
Cloudscape
con’t
 Some standard Java tools and utilities that
make it easier to use Cloudscape and to
develop Cloudscape applications
ij is Cloudscape's interactive JDBC scripting tool. It is
a simple utility for running scripts against a
Cloudscape database. You can also use it
interactively to run ad hoc queries. ij provides several
commands for ease in accessing a variety of JDBC
features.
 ij can be used in an embedded or a client/server
environment.
Cloudview is a graphical user interface for creating
and managing Cloudscape databases. It can be
used in an embedded or a client/server environment.
Cloudscape Database
 Consists of platform-independent files stored in
a directory that has the same name as the
database.
 Most of the Cloudscape tools are JDBC
applications.
 A JDBC application is one that uses the classes
in the java.sql package to interact with a DBMS.
 When we work with JDBC applications, we need
to know about the following two JDBC concepts
 Drivers
 Database connection URLs
Drivers
 Before a JDBC application interacts with a database, it must
cause the appropriate JDBC driver to be loaded in the Java
session. Cloudscape provides three JDBC drivers for use with
the Cloudscape database engine. When you use the
Cloudscape tools that are JDBC applications, you will need to
know which driver to load.
 COM.cloudscape.core.JDBCDriver For embedded
environments, when Cloudscape runs in the same JVM as the
application
 COM.cloudscape.core.WebLogicDriver For client/server
environments in which Cloudscape runs in the Cloudconnector
framework and applications connect via the network
 COM.cloudscape.core.RmiJdbcDriver For client/server
environments in which Cloudscape runs in the RmiJdbc Server
framework and applications connect via the network
Run as two different frameworks
•
Embedded
The simplest Cloudscape environment.
Enables Cloudscape as part of a Java application
Database accession as only one application at a time
No network access
Starting of an Cloudscape instance within the current JVM
and shutting down before completing
• Client/Server The connection to Cloudscape over the network.
Running embedded in a connectivity or server framework
allows multiple network connections.
The RmiJdbc framework enables the Cloudscape to execute
as a stand-alone database server
(a lightweight JDBC server and client)
 Each frame work directory has a bin subdirectory containing
batch files
A JDBC URL
 Provides a way of identifying a database so that the appropriate
driver recognizes it and connects to it. .
 After the driver is loaded, an application must specify the
correct database connection URL to connect to a specific
database.
The Cloudscape database connection URL allows us to
accomplish more tasks than simply connecting.
Some of them:
 jdbc:cloudscape: databaseName; CloudscapeURLAttributes
For embedded environments
 jdbc:cloudscape:weblogic: databaseName;
CloudscapeURLAttributes
 For connecting to Cloudscape running inside the Cloudconnector
framework, when the server is running on the default host localhost and
is using the default port number 7001
RmiJdbc Framework
 Change directories to bin directory in RmiJdbc
 Set the environment variables for the server
 Execution of the batch file setServerCloudscapeCP
 Launch the Cloudspace database server
 Execution of the batch file startCS
 Shut down the server
 Executiong stopCS
Cloudview
 Graphical user interface for creating and
managing Cloudscape databases.
Connecting to a Server
 You can use Cloudview as a client
application that interacts with Cloudscape
running in a server framework.
 To do that, simply load the appropriate
driver and use the appropriate protocol for
the server framework, either RmiJdbc or
Cloudconnector.
CLOUDSPACE
ORDBMS
• A Java and SQL based object-relational
database management system
Description: Founded in 1996, cloudspace is an Internet services company
specializing in open-source Website and online software development for the
entertainment, technology and professional services industries.
Url: http://www.cloudspace.com