Documente Academic
Documente Profesional
Documente Cultură
In this tutorial I will guide you through the steps to create your own Java Database Application
using an Oracle Database. To create a Java Application you will need at least some version of
Java on the machine that you are working on. To make this a more practical effort you should
also use a Java IDE. To create a Database Application you will also need a database. This
tutorial will use the “Oracle Database 10g Express Edition”. This database provides all the
functionality of a full commercial Oracle Database for an individual working on a local machine
work free of charge.
1) Setup Decisions
Evaluate the machine that you will use for your project.
You need a Java SDK (standard development kit) and a Java Application Server.
The most commonly available and supported components are generally in Java 2.
If you do not have Java on your machine download J2EE from sun which will install the
current updated Java 2 environment including the SDK and an Application Server.
J2EE link:
https://sdlc5c.sun.com/ECom/EComActionServlet;jsessionid=55115726FB21F17C8D1652ADA
1F4EE06
If you do:
You will need the server name and port number for it as well as a user name and
password.
If you don’t:
Download “Oracle Database 10g Express Edition” from Oracle and install it. Using the
installed administrator account create a user account with appropriate permissions.
http://www.oracle.com/technology/software/products/database/xe/index.html
You can choose to write your java classes by hand in a text editor and compile them to
create your application. With modern IDEs freely available this is a pretty senseless
waste of time.
In this tutorial I will show you the main steps to create your Oracle Java Application
using the NetBeans 5.5 Java IDE. If you have NetBeans on your machine then just follow
the steps shown. If you don’t have it, download it here:
http://www.netbeans.info/downloads/index.php
(If you have your own favorite Java IDE then you can also try to replicate the steps in this
tutorial in it.)
These come in the form of java libraries (packages) that can be imported in your java
programs. Example (after the first line in your code which is the package declaration,
after your import statements you can define your classes):
import oracle.sql.*;
For our purposes the “Oracle Database 10g Express Edition” database can be driven with
the following libraries:
import java.sql.*;
import oracle.jdbc.*;
import oracle.jdbc.pool.*;
import oracle.sql.*;
Check to see if you can import these libraries with your IDE because it may have been
included with your Java environment. (Another reason why IDEs are good.)
If not, then download an implementation of these libraries in the form of a jar file and add
a reference to it in your project before you try importing them in your code.
http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/htdocs/jdbc101040.html
Now you have all the components you need to implement any idea as a Java Oracle Database
Application. (All free and available with public support to play with!)
In this tutorial, our idea is a way for us, as a startup bookstore, to manage our inventory.
2) Implementation Steps
Our example intends to demonstrate how to complete SQL transactions between a Java
application and our Oracle database.
The extent of the specification to start us on this tutorial project is the following:
We will make a simple database of book entries that we will search by title in our
application. Our books database will consist of one table; with the following fields:
1. Use the Oracle Database administrator with the user account created for yourself to create
a books item table:
Logged in as user: SYS with password from installation
Add one more called Unique_ID and set it to be your primary key.
Choose Project
Choose a name for your project and uncheck the Create Main class option.
Adjust location to a place you know so if you have to come back to your work then you
know how. (In a school lab you might want to set this location to a shared drive where
you have access to a folder.)
BooksClientFrame.java
DataHandler.java
Error.java
Main.java
For our user interface I used some JLabels, a JList, and a JTextArea. You can design your
own interface by selecting the components you want from the Palette and dragging it to
the design area. By right clicking on a component in your design area you can also let the
IDE generate the methods associated for that control and place it into your code. (This is
only a method definition that is empty.)
An empty shell actionPerformed method used by our Submit button can be generated by
selecting Events and then Action from the items right click menu.
This is our Error form that displays different error messages from our application.
The following is the code for our application components:
Java Code:
BooksClientFrame.java
Refer to file called BooksClientFrame.java that came along with this tutorial.
Error.java
Refer to file called Error.java that came along with this tutorial.
3. Database Connectivity
Here I encourage you to make your own designs in the implementation of your version of this
example. To connect to data in a database from an application you will need the following
elements:
• An SQL data-reader
In my example I created a DataHandler object, which takes care of connectivity and gives me an
interface using the above elements.
For our Books database interface we use the DataHandler class. For our demonstration we need
at least a way to get a connection and a way to read the data. getDBConnection() and
DBRead(string stmt) fulfills this purpose. getDBConnection() setups a connection and
DBRead(string stmt) returns an SQL result set object based on the “stmt” argument, which in our
case is an SQL command made by the user interface form object (our BooksClientFrame.java
class).
Here is the code for our DataHandler project package item (our database interface class):
DataHandler.java
Refer to file called DataHandler.java that came along with this tutorial.
Once we have all the pieces we build the solution with the green triangle button on the IDE.
In NetBeans just press the green triangle button (without the red square in front of it; which is the
debug build version – I recommend trying this though, placing breakpoints in your code and
using the IDE’s debugging mode to step through your code line by line (if user command is next
then the debugger halts and waits for you to enter something into your application). This allows
you to check variables values in an actively running instance and see what you are doing.)
The highlighted statement in the editor (where the arrow is) is where execution is halted and you
have full control of the IDE in debug mode (explore this if you have time). As you can see the
“Watches” tab is highlighted in which I added by hand the rs.getString(1). During the first
instance of the program halting by my breakpoint the value of it can be seen. Using the blue
square buttons you can step through execution. Pressing the continue button continues execution
until it hits the next instance of our breakpoint or some other breakpoint in our code.
Running the Application:
Our java application after load (a build and a run; which is what the green triangle does):
As you can see the application displays all the items currently in our Books Oracle database upon
load.
(In a more real world scenario you would be interested in displaying other things as well along
with other functionality.)
4) Review
There is one serious potential structural problem. This is due to an omission in our tutorial
example. If this example were expanded into a larger application, the developer might run into
hard to understand run-time errors. Can you guess what this omission could be in our tutorial?
(The page after the Appendix section of this tutorial will have your answer.)
Appendix
Del:
Detectar idioma
▼
Al:
afrikaans
▼
Traducir
Si lo hace:
Necesitará el nombre del servidor y número de puerto para que lo
así como un nombre de usuario y contraseña.
Si no lo hacen:
Ver todas las letras de Oracle Database 10g Express Edition "de
Oracle e instalarlo. Uso de la instalación
cuenta de administrador crear una cuenta de usuario con
permisos adecuados.
"Oracle Database 10g Express Edition" link:
http://www.oracle.com/technology/software/products/data
base / xe / index.html
Ahora usted tiene todos los componentes que necesita para implementar
alguna idea de como Java de Oracle de base de datos de aplicaciones. (Todos los
gratuito y está disponible con el apoyo del público para jugar!)
En este tutorial, nuestra idea es una manera para nosotros, como
librería de inicio, para gestionar nuestro inventario.
2) Medidas de Aplicación
Nuestro ejemplo tiene la intención de demostrar cómo completar SQL
las transacciones entre una aplicación Java y Oracle nuestra
base de datos.
El alcance de la especificación para nosotros en este inicio
proyecto de tutorial es la siguiente:
Esta especificación del proyecto Tutorial:
Vamos a hacer una simple base de datos de anotaciones en cuenta que
buscará el título en nuestra aplicación. Nuestros libros
base de datos consistirá en una mesa, con las siguientes
campos:
Edición de Derecho de Autor Título Editorial
Precio
<item>
Paso 1: Crear el ejemplo de base de datos Libros
1. Utilice el administrador de base de datos Oracle con la
cuenta de usuario creada por sí mismo para crear un libro
tabla del artículo:
Nombre y ubicación
Código de Java:
BooksClientFrame.java
Error.java
3. Database Connectivity
Una vez que tengamos todas las piezas que construir la solución con
el botón triángulo verde en el IDE.
3) Depurar y Demo
Construir la aplicación:
En NetBeans sólo tiene que pulsar el botón triángulo verde
(Sin el cuadrado rojo en frente de ella, que es el
la versión de depuración - Recomiendo probar este, sin embargo,
colocar puntos de interrupción en el código y utilizando el IDE
modo de depuración para recorrer el código línea por línea
(Si es el próximo comando de usuario a continuación, se detiene el depurador y
espera a que escriba algo en su
aplicación). Esto le permite comprobar los valores de las variables
en una instancia activa en ejecución y ver lo que está
haciendo.)
Ejecutar la aplicación:
Nuestras aplicaciones Java después de la carga (a construir y ejecutar una;
que es lo que el triángulo verde hace):
Como se puede ver que sólo muestra los elementos con que el
nombre introducido, "Cómo programar C #". El único visible
resultado aquí es que se puede ver que hay 3 de
los elementos de la base de datos.
4) Revisar
Hay un grave problema estructural potencial. Este
se debe a una omisión en nuestro ejemplo tutorial. Si este
ejemplo, se expandió a una aplicación más grande, el
desarrollador podría encontrarse difícil de entender en tiempo de ejecución
errores. ¿Puedes adivinar lo que esta omisión podría estar en
nuestro tutorial?
(La página después de la sección de apéndice de este tutorial
tendrá su respuesta.)
Apéndice