<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Java(TM) Language Basics, Part 1, Lesson 7: Database Access and Permissions</TITLE>
<META NAME="AUTHOR" CONTENT="Monica Pawlan">
<META NAME="KEYWORDS" CONTENT="programming, basics, Java 2">
<META NAME="OWNER" CONTENT="Editorial/JDC">
<META NAME="revision" CONTENT="@(#)dba.src 1.27 03/09/00 JDC">
<STYLE TYPE="text/css">
<!--
CODE {font-family: Courier, Monospace;
font-size: 12pt}
PRE {font-family: Courier, Monospace;
font-size: 11pt}
-->
</STYLE>
</HEAD>
<!-- Start Body Insert-->
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#0000FF" ALINK="#FF0000" VLINK="#660066">
<!-- End Body Insert-->
<!-- Start PageTop Insert -->
<TABLE BORDER="0" CELLSPACING="0" CELLPADDING="0" WIDTH="100%">
<TR ALIGN="CENTER" VALIGN="TOP">
<TD WIDTH="157" ALIGN="LEFT">
<IMG SRC="/images/pixel.gif" HEIGHT="40" WIDTH="40" ALT="">
<A HREF="
http://java.sun.com/index.html"><IMG SRC="/images/javalogo52x88.gif" WIDTH="52" HEIGHT="88" ALT="Java Technology Home Page" BORDER="0"></A>
<BR>
<IMG SRC="/images/pixel.gif" WIDTH="157" HEIGHT="1" ALT=""></TD>
<TD>
<FORM NAME="seek1" METHOD="GET" ACTION="
http://search.java.sun.com/query.html">
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="0" WIDTH="100%">
<TR>
<TD ALIGN="RIGHT">
<IMG SRC="/images/stripelt.gif" WIDTH="6" HEIGHT="14" ALT=""></TD>
<TD WIDTH="100%">
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="0" WIDTH="100%">
<TR>
<TD BGCOLOR="#CC9966" WIDTH="100%">
<IMG SRC="/images/pixel.gif" HEIGHT="2" WIDTH="1" ALT=""></TD>
</TR>
<TR>
<TD>
<IMG SRC="/images/pixel.gif" HEIGHT="2" WIDTH="1" ALT=""></TD>
</TR>
<TR>
<TD BGCOLOR="#CC9966">
<IMG SRC="/images/pixel.gif" HEIGHT="2" WIDTH="1" ALT=""></TD>
</TR>
<TR>
<TD>
<IMG SRC="/images/pixel.gif" HEIGHT="2" WIDTH="1" ALT=""></TD>
</TR>
<TR>
<TD BGCOLOR="#CC9966">
<IMG SRC="/images/pixel.gif" HEIGHT="2" WIDTH="1" ALT=""></TD>
</TR>
<TR>
<TD>
<IMG SRC="/images/pixel.gif" HEIGHT="2" WIDTH="1" ALT=""></TD>
</TR>
<TR>
<TD BGCOLOR="#CC9966">
<IMG SRC="/images/pixel.gif" HEIGHT="2" WIDTH="1" ALT=""></TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="LEFT">
<IMG SRC="/images/stripert.gif" WIDTH="6" HEIGHT="14" ALT=""></TD>
<TD>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="0">
<TR>
<TD VALIGN="CENTER">
<A HREF="
http://java.sun.com/a-z/index.html"><IMG SRC="/images/azindex.gif" BORDER="0" WIDTH="72" HEIGHT="11" ALT="A-Z Index"></A></TD>
<TD VALIGN="CENTER">
<FONT FACE="Helvetica" SIZE="1">
<INPUT TYPE="text" SIZE="15" MAXLENGTH="128" NAME=qt></FONT></TD>
<TD VALIGN="CENTER">
<INPUT TYPE="image" SRC="/images/search.button.gif" WIDTH="55" HEIGHT="14" ALT="Search" value="search" BORDER="0"></TD>
</TR>
</TABLE>
</TD>
</TR>
</TABLE>
</FORM>
<P>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="0" CELLSPACING="0">
<TR VALIGN="TOP">
<TD WIDTH="100%"><IMG SRC="/images/chiclet.row.gif" WIDTH="55"
HEIGHT="18" ALT=""></TD>
<TD ROWSPAN="4" ALIGN="RIGHT" WIDTH="152">
<A HREF="/developer/index.html"><IMG SRC="/images/developer.connection.header.gif" BORDER="0" HEIGHT="42" WIDTH="319" ALT="Java Developer Connection(SM)"></A></TD>
</TR>
<TR VALIGN="TOP">
<TD BGCOLOR="#FFFFFF" HEIGHT="1" WIDTH="100%">
<IMG SRC="/images/pixel.gif" HEIGHT="1" WIDTH="1" ALT=""></TD>
</TR>
<TR VALIGN="TOP">
<TD BGCOLOR="#CC9966" HEIGHT="1" WIDTH="100%">
<IMG SRC="/images/pixel.gif" HEIGHT="1" WIDTH="1" ALT=""></TD>
</TR>
<TR VALIGN="TOP">
<TD><A HREF="/developer/onlineTraining/"><IMG SRC="/images/online-training.gif" WIDTH="165" HEIGHT="22" ALT="Online Training" BORDER=0></A></TD>
</TR>
</TABLE>
</TD>
</TR>
</TABLE>
<!-- End PageTop Insert -->
<!-- Start NavBar Insert -->
<TABLE BORDER="0" CELLSPACING="0" CELLPADDING="3" BGCOLOR="#FFFFFF" WIDTH="157" ALIGN="LEFT">
<!-- tab categories -->
<TR>
<TD><A HREF="
http://java.sun.com/products/"><IMG SRC="/images/side.tab.products.gif" HEIGHT="15" WIDTH="130" BORDER="0" ALT="Downloads, APIs, Documentation"></A></TD>
</TR>
<TR>
<TD><A HREF="/developer/index.html"><IMG SRC="/images/side.tab.developer.gif" HEIGHT="15" WIDTH="130" BORDER="0" ALT="Java Developer Connection"></A></TD>
</TR>
<TR>
<TD><A HREF="/developer/infodocs/index.shtml"><IMG SRC="/images/side.tab.docs.gif" HEIGHT="15" WIDTH="130" BORDER="0" ALT="Tutorials, Tech Articles, Training"></A></TD>
</TR>
<TR>
<TD><A HREF="/developer/support/index.html"><IMG SRC="/images/side.tab.support.gif" HEIGHT="15" WIDTH="130" BORDER="0" ALT="Online Support"></A></TD>
</TR>
<TR>
<TD><A HREF="/developer/community/index.html"><IMG SRC="/images/side.tab.community.gif" HEIGHT="15" WIDTH="130" BORDER="0" ALT="Community Discussion"></A></TD>
</TR>
<TR>
<TD><A HREF="
http://java.sun.com/industry/"><IMG SRC="/images/side.tab.news.gif" HEIGHT="15" WIDTH="130" BORDER="0" ALT="News & Events from Everywhere"></A></TD>
</TR>
<TR>
<TD><A HREF="
http://java.sun.com/solutions"><IMG SRC="/images/side.tab.solutions.gif" HEIGHT="15" WIDTH="130" BORDER="0" ALT="Products from Everywhere"></A></TD>
</TR>
<TR>
<TD><A HREF="
http://java.sun.com/casestudies"><IMG SRC="/images/side.tab.case.gif" HEIGHT="15" WIDTH="130" BORDER="0" ALT="How Java Technology is Used Worldwide"></A></TD>
</TR>
<TR>
<TD> <DIV ALIGN="RIGHT">
<A HREF="/servlet/PrintPageServlet"><IMG SRC="/images/printbutton.gif" WIDTH="155" HEIGHT="25" ALT="Print Button" BORDER="0"></A>
</DIV>
</TD>
</TR>
<TR><TD> </TD></TR>
<!-- End NavBar Insert -->
<!-- START SUB-NAV -->
<TR>
<TD><!-- INSERT SUB-NAV INFO -->
</TD>
</TR>
<!-- END SUB-NAV -->
</TABLE>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="0">
<TR>
<TD>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<!-- Template Version 2.0 -->
<!-- ================== -->
<!-- Start Main Content -->
<!-- ================== -->
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="0">
<TR>
<TD VALIGN="TOP">
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A NAME="top"></A>
<DIV ALIGN="RIGHT">
<FONT SIZE="-1"><A HREF="/developer/onlineTraining/index.html">Training Index</A></FONT>
<H2>Java<FONT SIZE="-2"><SUP>TM</SUP></FONT> Programming Language Basics, Part 1<BR>
<FONT SIZE="3">Lesson 7: Database Access and Permissions</FONT></H2>
<FONT SIZE="-1">[<A HREF="data.html"><<BACK</A>] [<A HREF="index.html#contents">CONTENTS</A>] [<A HREF="rmi.html">NEXT>></A>]</FONT></DIV>
<P>
This lesson converts the application, applet, and servlet
examples from Lesson 6 to write to and read from a database
using JDBC<FONT SIZE="-2"><SUP>TM</SUP></FONT>. JDBC is
the Java<FONT SIZE="-2"><SUP>TM</SUP></FONT> database connectivity
application programming interface (API) available in the
Java® 2 Platform software.
<P>
The code for this
lesson is very similar to the code you saw in Lesson 6, but
additional steps (beyond converting the file access code to database access
code) include setting up the environment, creating a database table, and
connecting to the database. Creating a database table is a database
administration task that is not part of your program code. However,
establishing a database connection and the resulting database access
are.
<P>
As in Lesson 6, the applet needs appropriate permissions to
connect to the database. Which permissions it needs varies
with the type of driver used to make the database connection.
<UL>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="#setup">Database Setup</A></FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="#db">Create Database Table</A></FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="#app">Database Access by Applications</A></FONT>
<UL>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="#estab">Establishing a Connection</A></FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="#final">Final and Private Variables</A></FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="#rw">Writing and Reading Data</A></FONT>
</UL>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="#applet">Database Access by Applets</A></FONT>
<UL>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="#jdbc">JDBC Driver</A></FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="#odbc">JDBC-ODBC Bridge with ODBC Driver</A></FONT>
</UL>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="#serv">Database Access by Servlets</A></FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="#more">More Information</A></FONT>
</UL>
<HR>
<A NAME="setup"></A>
<H3>Database Setup</H3>
You need access to a database if you want to run the examples
in this lesson. You can install a database on your machine or perhaps
you have access to a database at work. Either way, you need a
database driver and any relevant environment settings so your program
can load the driver and locate the database. The program will
also need database login information in the form of a user name
and password.
<P>
A database driver is software that lets a program establish a
connection with a database. If you do not have the right driver for
the database to which you want to connect,
your program will be unable to establish the connection.
<P>
Drivers either come with the database or are
available from the Web. If you install your own database, consult
the documentation for the driver for information on installation
and any other environment settings you
need for your platform. If you are using a database at work,
consult your database administrator for this information.
<P>
To show you two ways to do it, the application example uses
the <CODE>jdbc</CODE> driver, the applet examples use the
<CODE>jdbc</CODE> and <CODE>jdbc.odbc</CODE> drivers, and the servlet
example uses the <CODE>jdbc.odbc</CODE> driver. All examples connect to
an <CODE>OracleOCI7.3.4</CODE> database.
<P>
Connections to other databases will involve similar steps and
code. Be sure to consult your documentation or system
administrator if you need help connecting to the database.
<A NAME="db"></A>
<H3>Create Database Table</H3>
Once you have access to a database, create a table in it
for the examples in this lesson. You need a table with one
text field for storing character data.
</FONT>
<PRE>
TABLE DBA (
TEXT varchar2(100),
primary key (TEXT)
)
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A NAME="app"></A>
<H3>Database Access by Applications</H3>
This example converts the <A HREF="./Code/FileIO.java">FileIO</A>
program from Lesson 6 to write data to and read data from
a database. The top window below appears when you start
the <A HREF="./Code/Dba.java">Dba</A> application, and the window
beneath it appears when you click the <CODE>Click Me</CODE> button.
<P>
When you click the <CODE>Click Me</CODE> button, whatever is
entered into the text field is saved to
the database. After that, the data is retrieved from the
database and displayed in the window shown on the bottom. If you write
data to the table more than once, everything written is read and displayed
in the window shown on the bottom, so you might have to enlarge the window
to see the entire list of table items.
<P>
<CENTER>
<IMG SRC="./Art/dba1.gif" WIDTH="252" HEIGHT="129" ALT="">
<P>
When Application Starts
<P>
<IMG SRC="./Art/dba2.gif" WIDTH="247" HEIGHT="157" ALT="">
<P>
After Writing Orange and Apple to Database</CENTER>
<P>
The database access application needs code to establish the
database connection and do the database read and write operations.
<A NAME="estab"></A>
<H4>Establishing a Database Connection</H4>
The JDBC <CODE>DriverManager</CODE> class can handle multiple database
drivers, and initiates all database communication.
To load the driver and connect to the database, the application needs
a <CODE>Connection</CODE> object and <CODE>Strings</CODE> that
represent the <CODE>_driver</CODE> and <CODE>_url</CODE>.
<P>
The <CODE>_url</CODE> string is in the form of a Uniform
Resource Locator (URL). It consists of the URL, Oracle subprotcol,
and Oracle data source in the form <CODE>jdbc:oracle:thin</CODE>, the database
login <CODE>username</CODE>, the <CODE>password</CODE>, plus machine,
port, and protocol information.
</FONT>
<PRE>
private Connection c;
final static private String _driver =
"oracle.jdbc.driver.OracleDriver";
final static private String _url =
"jdbc:oracle:thin:username/password@(description=(
address_list=(address=(protocol=tcp)
(host=developer)(port=1521)))
(source_route=yes)(connect_data=(sid=jdcsid)))";
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<P>
The <CODE>actionPerformed</CODE> method calls the
<CODE>Class.forName(_driver)</CODE> method to load
the driver, and the <CODE>DriverManager.getConnection</CODE> method
to establish the connection.
The <A HREF="data.html#excep">Exception Handling</A>
section in Lesson 6 describes <CODE>try</CODE> and <CODE>catch</CODE>
blocks. The only thing different here is that this block
uses two <CODE>catch</CODE> statements because
two different errors are possible.
<P>
The call to <CODE>Class.forName(_driver);</CODE> throws
<CODE>java.lang.ClassNotFoundException</CODE>, and the call
to <CODE>c = DriverManager.getConnection(_url);</CODE>
throws <CODE>java.sql.SQLException</CODE>. In the case
of either error, the application tells the user what is
wrong and exits because the program cannot operate in
any meaningful way without a database driver or connection.
</FONT>
<PRE>
public void actionPerformed(ActionEvent event){
try{
//Load the driver
Class.forName(_driver);
//Establish database connection
c = DriverManager.getConnection(_url);
}catch (java.lang.ClassNotFoundException e){
System.out.println("Cannot find driver class");
System.exit(1);
}catch (java.sql.SQLException e){
System.out.println("Cannot get connection");
System.exit(1);
}
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A NAME="final"></A>
<H4>Final and Private Variables</H4>
The member variables used to establish the database connection above are
declared <CODE>private</CODE>, and two of those variables are also
declared <CODE>final</CODE>.
<P>
<STRONG>final</STRONG>:
A <CODE>final</CODE> variable contains
a constant value that can never change once it is initialized. In
the example, the user name, and password are <CODE>final</CODE>
variables because you would not want to allow an instance
of this or any other class to change this information.
<P>
<STRONG>private</STRONG>:
A <CODE>private</CODE> variable can only be
used (accessed) by the class in which it is declared. No other class
can read or change <CODE>private</CODE> variables. In the example, the
database driver, user name, and password variables are
<CODE>private</CODE> to prevent an outside class from accessing
them and jeopardizing the database connection, or compromising
the secret user name and password information.
You can find more information on this in the
<A HREF="
http://java.sun.com/docs/books/tutorial/java/javaOO/index.html">Objects
and Classs</A> lesson in
<A HREF="
http://java.sun.com/docs/books/tutorial">The Java Tutorial</A>
<A NAME="rw"></A>
<H4>Writing and Reading Data</H4>
In the write operation, a
<CODE>Statement</CODE> object is created from the <CODE>Connection</CODE>.
The <CODE>Statement</CODE> object has methods for executing SQL queries
and updates. Next, a <CODE>String</CODE> object that contains
the SQL update for the write operation is constructed and
passed to the <CODE>executeUpdate</CODE> method of the
<CODE>Statement</CODE> object.
</FONT>
<PRE>
Object source = event.getSource();
if(source == button){
JTextArea displayText = new JTextArea();
try{
//Code to write to database
String theText = textField.getText();
Statement stmt = c.createStatement();
String updateString = "INSERT INTO dba VALUES
('" + theText + "')";
int count = stmt.executeUpdate(updateString);
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
SQL commands are <CODE>String</CODE> objects, and therefore, follow
the rules of <CODE>String</CODE> construction where the string
is enclosed in double quotes (" ") and variable data is appended with a
plus (+). The variable <CODE>theText</CODE> has single and double quotes
to tell the database the SQL string has variable rather than literal
data.
<P>
In the read operation, a <CODE>ResultSet</CODE> object is created
from the <CODE>executeQuery</CODE> method of the
<CODE>Statement</CODE> object. The <CODE>ResultSet</CODE>
contains the data returned by the query. To retrieve the
data returned, the code iterates through the <CODE>ResultSet</CODE>,
retrieves the data, and appends the data to the text area,
<CODE>displayText</CODE>.
</FONT>
<PRE>
//Code to read from database
ResultSet results = stmt.executeQuery(
"SELECT TEXT FROM dba ");
while(results.next()){
String s = results.getString("TEXT");
displayText.append(s + "\n");
}
stmt.close();
} catch(java.sql.SQLException e){
System.out.println(e.toString());
}
//Display text read from database
panel.removeAll();
panel.add("North", clicked);
panel.add("Center", displayText);
panel.add("South", clickButton);
panel.validate();
panel.repaint();
}
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A NAME="applet"></A>
<H3>Database Access by Applets</H3>
The applet version of the example is like the application code described
above except for the standard differences between applications and applets
described in the <A HREF="applet.html#struct">Structure and Elements</A>
section of Lesson 3.
<P>
However, if you run the applet without a policy file, you get
a stack trace indicating permission errors.
The <A HREF="data.html#sec">Granting Applets Permission</A> section
in Lesson 6 introduced you to policy files and how to launch an
applet with the permission it needs. The Lesson 6 applet example
provided the policy file and told you how to launch the applet
with it. This lesson shows you how to read the stack trace to
determine the permissions you need in a policy file.
<P>
To keep things interesting, this lesson has two versions
of the database access applet: one uses the JDBC driver,
and the other uses the the JDBC-ODBC bridge with an
Open DataBase Connectivity (ODBC) driver.
<P>
Both applets do the same operations to the same database
table using different drivers. Each applet has its own policy file
with different permission lists and has different
requirements for locating the database driver
<A NAME="jdbc"></A>
<H4>JDBC Driver</H4>
The JDBC driver is used from a program written exclusively
in the Java language (Java program). It
converts JDBC calls directly into the protocol
used by the DBMS. This type of driver is available from
the DBMS vendor and is usually packaged with the DBMS
software.
<P>
<STRONG>Starting the Applet:</STRONG>
To successfully run, the <A HREF="./Code/DbaAppl.java">DbaAppl.java</A>
applet needs an available database driver and a policy file.
This section walks through the steps to get everything set up.
Here is the <CODE>DbaAppl.html</CODE> file for running
the <CODE>DbaAppl</CODE> applet:
</FONT>
<PRE>
<HTML>
<BODY>
<APPLET CODE=DbaAppl.class
WIDTH=200
HEIGHT=100>
</APPLET>
</BODY>
</HTML>
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<P>
And here is how to start the applet with appletviewer:
</FONT>
<PRE>
appletviewer DbaAppl.html
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<P>
<STRONG>Locating the Database Driver:</STRONG>
Assuming the driver is not available to the <CODE>DriverManager</CODE>
for some reason, the following error generates when you click the
<CODE>Click Me</CODE> button.
</FONT>
<PRE>
cannot find driver
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
This error means the DriverManager looked for the JDBC driver in the
directory where the applet HTML and class files are and could not find it.
To correct this error, copy the driver to the directory
where the applet files are, and if the driver is bundled in a zip file,
unzip the zip file so the applet can access the driver.
<P>
Once you have the driver in place, launch the applet again.
</FONT>
<PRE>
appletviewer DbaAppl.html
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A NAME="perm"></A>
<STRONG>Reading a Stack Trace:</STRONG>
Assuming the driver is locally available to the applet, if the
<A HREF="./Code/DbaAppl.java">DbaAppl.java</A> applet
is launched without a policy file, the following stack trace
is generated when the end user clicks the <CODE>Click Me</CODE>
button.
</FONT>
<PRE>
java.security.AccessControlException: access denied
(java.net.SocketPermission developer resolve)
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
The first line in the above stack trace tells you access is denied.
This means this stack trace was generated because the applet tried to
access a system resource without the proper permission.
The second line means to correct this condition
you need a <CODE>SocketPermission</CODE> that gives
the applet access to the machine (<CODE>developer</CODE>) where
the database is located.
<P>
You can use Policy tool to create the policy file you need,
or you can create it with an ASCII editor. Here is the policy
file with the permission indicated by the stack trace:
</FONT>
<PRE>
grant {
permission java.net.SocketPermission "developer",
"resolve";
"accessClassInPackage.sun.jdbc.odbc";
};
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<P>
Run the applet again, this time with a policy file named
<CODE>DbaApplPol</CODE> that has the above permission in it:
</FONT>
<PRE>
appletviewer -J-Djava.security.policy=DbaApplPol
DbaAppl.html
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
You get a stack trace again, but this time it is a different
error condition.
</FONT>
<PRE>
java.security.AccessControlException: access denied
(java.net.SocketPermission
129.144.176.176:1521 connect,resolve)
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
Now you need a <CODE>SocketPermission</CODE> that allows access to the
Internet Protocol (IP) address and port on the <CODE>developer</CODE>
machine where the database is located.
<P>
Here is the <CODE>DbaApplPol</CODE> policy file with the permission
indicated by the stack trace added to it:
</FONT>
<PRE>
grant {
permission java.net.SocketPermission "developer",
"resolve";
permission java.net.SocketPermission
"129.144.176.176:1521", "connect,resolve";
};
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
Run the applet again. If you use the above policy file
with the Socket permissions indicated, it works just fine.
</FONT>
<PRE>
appletviewer -J-Djava.security.policy=DbaApplPol
DbaAppl.html
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A NAME="odbc"></A>
<H4>JDBC-ODBC Bridge with ODBC Driver</H4>
Open DataBase Connectivity (ODBC) is Microsoft's programming
interface for accessing a large number of relational databases on
numerous platforms. The JDBC-ODBC bridge is built into the Solaris
and Windows versions of the Java platform so you can do two
things:
<OL>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">Use ODBC from a Java program</FONT>
<P>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">Load ODBC drivers as
JDBC drivers.
This example uses the JDBC-ODBC bridge to load an ODBC driver
to connect to the database. The applet has no ODBC code, however.</FONT>
</OL>
<P>
The <CODE>DriverManager</CODE> uses environment settings to
locate and load the database driver. For this example,
the driver file does not need to be locally accessible.
<P>
<STRONG>Start the Applet:</STRONG>
Here is the <CODE>DbaOdb.html</CODE> file for running the
<CODE>DbaOdbAppl</CODE> applet:
</FONT>
<PRE>
<HTML>
<BODY>
<APPLET CODE=DbaOdbAppl.class
WIDTH=200
HEIGHT=100>
</APPLET>
</BODY>
</HTML>
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
And here is how to start the applet:
</FONT>
<PRE>
appletviewer DbaOdb.html
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<P>
<STRONG>Reading a Stack Trace:</STRONG>
If the <A HREF="./Code/DbaOdbAppl.java">DbaOdbAppl.java</A> applet
is launched without a policy file, the following stack trace
is generated when the end user clicks the <CODE>Click Me</CODE>
button.
</FONT>
<PRE>
java.security.AccessControlException: access denied
(java.lang.RuntimePermission
accessClassInPackage.sun.jdbc.odbc )
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
The first line in the above stack trace tells you access is denied.
This means this stack trace was generated because the applet tried to
access a system resource without the proper permission. The second
line means you need a <CODE>RuntimePermission</CODE> that gives
the applet access to the <CODE>sun.jdbc.odbc</CODE> package.
This package provides the JDBC-ODBC bridge functionality to the
Java<A HREF="#TJVM"><SUP>1</SUP></A> virtual machine (VM).
<P>
You can use Policy tool to create the policy file you need,
or you can create it with an ASCII editor. Here is the policy
file with the permission indicated by the stack trace:
</FONT>
<PRE>
grant {
permission java.lang.RuntimePermission
"accessClassInPackage.sun.jdbc.odbc";
};
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<P>
Run the applet again, this time with a policy file named
<CODE>DbaOdbPol</CODE> that has the above permission in it:
</FONT>
<PRE>
appletviewer -J-Djava.security.policy=DbaOdbPol
DbaOdb.html
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
You get a stack trace again, but this time it is a different
error condition.
</FONT>
<PRE>
java.security.AccessControlException:
access denied (java.lang.RuntimePermission
file.encoding read)
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
The stack trace means the applet needs read permission to the encoded
(binary) file.
Here is the <CODE>DbaOdbPol</CODE> policy file with the permission
indicated by the stack trace added to it:
</FONT>
<PRE>
grant {
permission java.lang.RuntimePermission
"accessClassInPackage.sun.jdbc.odbc";
permission java.util.PropertyPermission
"file.encoding", "read";
};
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
Run the applet again. If you use the above policy file
with the Runtime and Property permissions indicated, it
works just fine.
</FONT>
<PRE>
appletviewer -J-Djava.security.policy=DbaOdbPol
DbaOdb.html
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A NAME="serv"></A>
<H3>Database Access by Servlets</H3>
As you learned in Lesson 6, servlets are under the security
policy in force for the web server under which they run. When
the database read and write code is added to the
<CODE>FileIOServlet</CODE> from Lesson 6, the
<A HREF="./Code/DbaServlet.java">DbaServlet.java</A> servlet
for this lesson executes without restriction under Java WebServer<FONT SIZE="-2"><SUP>TM</SUP></FONT> 1.1.1.
<P>
The web server has to be configured to locate the
database. Consult your web server documentation or
database administrator for help. With Java WebServer 1.1.1,
the configuration setup involves editing the startup scripts
with such things as environment settings for loading the ODBC driver,
and locating and connecting to the database.
<P>
<IMG SRC="./Art/dba1.gif" WIDTH="252" HEIGHT="129" ALT="">
<TABLE BORDER="0" CELLSPACING="2" CELLPADDING="2">
<TR><TD>
<IMG SRC="./Art/dba2.gif" WIDTH="247" HEIGHT="157" ALT="">
</TD></TR>
</TABLE>
</FONT>
<PRE>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.net.*;
import java.io.*;
public class DbaServlet extends HttpServlet {
private Connection c;
final static private String _driver =
"sun.jdbc.odbc.JdbcOdbcDriver";
final static private String _user = "username";
final static private String _pass = "password";
final static private String
_url = "jdbc:odbc:jdc";
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<title>Example<title>" +
"<body bgcolor=FFFFFF>");
out.println("<h2>Button Clicked</h2>");
String DATA = request.getParameter("DATA");
if(DATA != null){
out.println("<STRONG>Text from
form:</STRONG>");
out.println(DATA);
} else {
out.println("No text entered.");
}
//Establish database connection
try{
Class.forName (_driver);
c = DriverManager.getConnection(_url,
_user,
_pass);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
try{
//Code to write to database
Statement stmt = c.createStatement();
String updateString = "INSERT INTO dba " +
"VALUES ('" + DATA + "')";
int count = stmt.executeUpdate(updateString);
//Code to read from database
ResultSet results = stmt.executeQuery(
"SELECT TEXT FROM dba ");
while(results.next()){
String s = results.getString("TEXT");
out.println("<BR>
<STRONG>Text from database:</STRONG>");
out.println(s);
}
stmt.close();
}catch(java.sql.SQLException e){
System.out.println(e.toString());
}
out.println("<P>Return to
<A HREF="../dbaHTML.html">Form</A>");
out.close();
}
}
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A NAME="more"></A>
<H3>More Information</H3>
You can find more information on variable access settings in the
<A HREF="
http://java.sun.com/docs/books/tutorial/java/javaOO/index.html">Objects
and Classes</A> trail in
<A HREF="
http://java.sun.com/docs/books/tutorial">The Java Tutorial</A>
<P>
_______<BR>
<A NAME="TJVM"><SUP>1</SUP></A> As used on this web site,
the terms "Java virtual
machine" or "JVM" mean a virtual machine
for the Java platform.
<P ALIGN="RIGHT">
<FONT SIZE="-1">[<A HREF="#top">TOP</A>]</FONT>
</FONT>
</TD>
</TR>
</TABLE>
<!-- ================ -->
<!-- End Main Content -->
<!-- ================ -->
</FONT>
</TD>
</TR>
</TABLE>
<!-- Copyright Insert -->
<BR CLEAR="ALL">
<FORM ACTION="/cgi-bin/search.cgi" METHOD="POST">
<TABLE WIDTH="100%" CELLPADDING="0" BORDER="0" CELLSPACING="5">
<TR>
<TD VALIGN="BOTTOM">
</TD>
</TR>
<A HREF="/servlet/PrintPageServlet"><IMG SRC="/images/printbutton.gif" WIDTH="155" HEIGHT="25" ALT="Print Button" BORDER="0"></A>
<CENTER>
<FONT SIZE="-1" COLOR="#999999" FACE="Verdana, Arial, Helvetica, sans-serif">
[ This page was updated: <!-- new date --> 31-Mar-2000 ]
</font></CENTER>
</TD>
</TR>
<TR>
<TD BGCOLOR="#CCCCCC">
<IMG SRC="/images/pixel.gif" HEIGHT="1" WIDTH="1" ALT=""></TD>
</TR>
<TR>
<TD>
<CENTER>
<FONT SIZE="-2" FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="
http://java.sun.com/products/">Products & APIs</A> |
<A HREF="/developer/index.html">Developer Connection</A> |
<A HREF="/developer/infodocs/index.shtml">Docs & Training</A> |
<A HREF="/developer/support/index.html">Online Support</A><BR>
<A HREF="/developer/community/index.html">Community Discussion</A> |
<A HREF="
http://java.sun.com/industry/">Industry News</A> |
<A HREF="
http://java.sun.com/solutions">Solutions Marketplace</A> |
<A HREF="
http://java.sun.com/casestudies">Case Studies</A>
</FONT>
</CENTER>
</TD>
</TR>
<TR>
<TD BGCOLOR="#CCCCCC">
<IMG SRC="/images/pixel.gif" HEIGHT="1" WIDTH="1" ALT=""></TD>
</TR>
<TR>
<TD ALIGN="CENTER">
<FONT SIZE="-2" FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="
http://java.sun.com/docs/glossary.html">Glossary</A> -
<A HREF="
http://java.sun.com/applets/">Applets</A> -
<A HREF="
http://java.sun.com/docs/books/tutorial/">Tutorial</A> -
<A HREF="
http://java.sun.com/jobs/">Employment</A> -
<A HREF="
http://java.sun.com/nav/business/">Business & Licensing</A> -
<A HREF="
http://java.sun.com/javastore/">Java Store</A> -
<A HREF="
http://java.sun.com/casestudies/">Java in the Real World</A>
</FONT>
</TD>
</TR>
<TR>
<TD>
<CENTER>
<FONT SIZE="-2" FACE="Verdana, Arial, Helvetica, sans-serif">
<a href="/siteinfo/faq.html">FAQ</a> |
<a href="/feedback/index.html">Feedback</a> |
<a href="
http://www.dynamicdiagrams.net/mapa/cgi-bin/help.tcl?db=javasoft&dest=
http://java.sun.com/">Map</a> |
<A HREF="
http://java.sun.com/a-z/index.html">A-Z Index</A>
</FONT>
</CENTER>
</TD>
</TR>
<TR>
<TD>
<TABLE WIDTH="100%" CELLPADDING="0" BORDER="0" CELLSPACING="0">
<TR>
<TD WIDTH="50%">
<FONT SIZE="-2" FACE="Verdana, Arial, Helvetica, sans-serif">
For more information on Java technology<BR>
and other software from Sun Microsystems, call:<BR>
</FONT>
<FONT SIZE="-1" FACE="Verdana, Arial, Helvetica, sans-serif">
(800) 786-7638<BR></FONT>
<FONT SIZE="-2" FACE="Verdana, Arial, Helvetica, sans-serif">
Outside the U.S. and Canada, dial your country's
<A HREF="
http://www.att.com/business_traveler/attdirecttollfree/">AT&T Direct Access Number</A> first.<BR>
</FONT>
</TD>
<TD ALIGN="RIGHT" WIDTH="50%">
<A HREF="
http://www.sun.com"><IMG SRC="/images/lgsun.gif" width="64" height="30" border="0" ALT="Sun Microsystems, Inc."></A><BR>
<FONT SIZE="-2" FACE="Verdana, Arial, Helvetica, sans-serif">
Copyright © 1995-2000
<A HREF="
http://www.sun.com">Sun Microsystems, Inc.</A><BR>
All Rights Reserved.
<A HREF="
http://www.sun.com/share/text/termsofuse.html">Terms of Use</A>.
<A HREF="
http://www.sun.com/privacy/">Privacy Policy</A>.
</FONT>
</TD>
</TR>
</TABLE>
</TD>
</TR>
</TABLE>
</FORM>
<!-- End Copyright Insert -->
</BODY>
</HTML>