|
Letzte
Bearbeitung dieses Dokuments: |
Code
Erklärungen
und Anwendungsbeispiele
Verwandte
Dokumentation
package
js_base.connections;
/*
*
de: Package mit Klassen für den Zugriff auf
Datenbanken.
* en: Package with classes to access
databases. */
import
java.sql.*;
/*
*
de: Package mit Klassen für verschiedene Aufgaben;
z.B. Erstellen eines Vector.
* en: Package with
classes for various tasks; e.g. create a Vector. */
import
java.util.*;
/*
*
de:
* Klasse mit dem Start-Frame
(CommandCenter).
* en:
* Class
with the start-frame (CommandCenter). */
import
js_base.frame.JSBS_StartFrame;
/*
*
de:
* Klasse mit den Parametern zur
Steuerung des Anwendungsprogramms.
* en:
*
Class with parameters to controll the application. */
import
js_base.structures.JSBS_UniversalParameters;
/*
*
de: JSBS-Package
mit Klassen mit XML-Strukturen für das Einlesen von
Parametern.
* en: JSBS-package with classes with
XML-structures to read external parameters. */
import
js_base.xml.*;
/**
*
* @author kurt[at]javascout(dot)biz
* @date
2006-09-22
*
* @description
* de:
*
Klasse mit Methoden zum Erstellen und Verwalten von
Verbindungen zum Datenbanksystem.
* Diese Methoden
verfolgen alle Verbindungen zur Datenbank.
* Da das
Erstellen einer Verbindung zur Datenbank relativ lang dauert, werden
nicht
* mehr verwendete Verbindungen nicht
'geschlossen' sondern als 'unbenutzt' markiert
* und
wieder verwendet wenn eine neue Anforderung für eine
Datenbank-Verbindung
* (durch die Methode
'reserveConnection') gegeben ist.
* en:
*
Class with methods to establish and administrate connections to
the database-system.
* This methods keeps track
of all connections to the database.
* As
establishing of a connection to the database takes relatively
long,
* no longer needed connections are not
'closed'; just marked as unused
* and used again
at a new request for a database-connection (method
'reserveConnection').
*
* @change-log
*
when who why
*
--------------------------------------------------------
*
*/public
class
JSBS_DB_ConnectionManager
{
/*
*
VARIABLE / VARIABLES.
* -------------------- */
/*
*
de: Vector mit den hergestellten Verbindungen zur Datenbank.
*
en: Vector with all established connections to the database.
*/
private
Vector
vecEstablishedConnections
=
new
Vector();
/*
*
de:
* Vector mit den Methoden-Namen die eine Verbindung zur
Datenbank angefordert
* haben.
* Eine leere
Zeichenkette bedutet, dass die zugehörige Connection
*
(in vecEstablishedConnections) nicht verwendet wird und neu vergeben
werden kann.
* en:
* Vector with the method-names
that requested a database-connection.
* An empty string
means, that the corresponding connection (in
vecEstablishedConnections)
* is unused and can be
reassigned. */
private
Vector
vecConnectionUsers
=
new
Vector();
/*
*
de: XML-Struktur mit den Parametern für die Verbindung zur
Datenbank.
* en: XML-structure with the parameters for the
connection to the database. */
private
JSBS_XML_Connections
structJSBS_XML_Connections
;
/*
*
de: Status-Code; damit kann eine aufrufende Methode prüfen ob
ein fehler aufgetreten ist.
* en: Status-Code; with that a
calling method can check if an error occured. */
public
int
StatusCode
=
0;
/*
* de: Status-Nachricht um den Text eines Datenbank-Fehlers
zurück liefern zu können.
* en: Status-Message to
return the text of a database-error. */
public
String
StatusMsg
=
""
;
/*
*
**********
* de: Konstanten für mögliche
Status-Code die in dieser Klasse auftreten können.
*
en: Constants for possible Status-Codes happening in this class.
*/
static
final int
CONST_STATUS_OK
=
0;
static
final int
CONST_DATABASE_CONNECTION_BROKE
=
1;
static
final int
CONST_DATABASEDRIVERNAME_ELEMENT_MISSING
=
2;
static
final int
CONST_DATABASENAME_ELEMENT_MISSING
=
3;
static
final int
CONST_DATABASEUSERID_ELEMENT_MISSING
=
4;
static
final int
CONST_DATABASEPASSWORD_ELEMENT_MISSING
=
5;
static
final int
CONST_DATABASEDRIVER_LOAD_FAILED
=
11;
static
final int
CONST_DATABASE_CONNECTION_FAILED
=
12;
static
final int
CONST_CLASS_MISSMATCH
=
21;
static
final int
CONST_INVALID_REFERENCE
=
22;
static
final int
CONST_UNKNOWN_ERROR
=
999;
/*
*
de:
* Offset (Verschiebung) für Status-Codes die von
der Methode zum Lesen der Parameter-Datei
* zurück
geliefert werden.
* en:
* Offset for Status-Codes
returned by the method to read the parameter-file. */
static
final int
CONST_XML_STATUS_OFFSET
=
100;
/*
* KONSTRUKTOR
der Klasse / CONSTURCTOR of the class
* --------------------
*/
public
JSBS_DB_ConnectionManager(JSBS_StartFrame
parmCC) {
/*
*
de: Text der Status-Nachricht leeren.
* en: Erase the text
of the Status-Message. */
StatusMsg
=
""
;
/*
*
de:
* Initialisieren der XML-Struktur mit den Parametern für
die Verbindung zur Datenbank;
* der Konstruktor der Klasse
enthält das Lesen der Datei mit der XML-Struktur.
*
en:
* Initialize the XML-structure with the parameters for
Database-Connection;
* the Constructur of the class
includes reading the file with the XML-structure.
*/
structJSBS_XML_Connections
=
new
JSBS_XML_Connections(parmCC);
/*
*
de:
* Prüfen des Status der gerade initialisierten
Struktur und einen eventuellen Fehler
* an die aufrufende
Methode zurück liefern.
* en:
* Check the
status of the just initialized structure and report an error to the
calling method. */
if
(
structJSBS_XML_Connections
.
StatusCode
==
JSBS_XML_Constants.
CONST_OK
)
{
StatusCode
=
CONST_STATUS_OK
;
}
else
{
StatusCode
=
CONST_XML_STATUS_OFFSET
+
structJSBS_XML_Connections
.
StatusCode
;
return
;
}/*
*
de: Prüfen, dass alle benötigten Parameter vorhanden
sind.
* en: Check that all needed parameters are present.
*/
if
(
structJSBS_XML_Connections
.getDataBaseDriverName()
==
null
)
{
StatusCode
=
CONST_DATABASEDRIVERNAME_ELEMENT_MISSING
;
return
;
}/*
*/
if
(
structJSBS_XML_Connections
.getDataBaseName()
==
null
)
{
StatusCode
=
CONST_DATABASENAME_ELEMENT_MISSING
;
return
;
}/*
*/
if
(
structJSBS_XML_Connections
.getDataBaseUserID()
==
null
)
{
StatusCode
=
CONST_DATABASEUSERID_ELEMENT_MISSING
;
return
;
}/*
*/
if
(
structJSBS_XML_Connections
.getDataBasePassword()
==
null
)
{
StatusCode
=
CONST_DATABASEPASSWORD_ELEMENT_MISSING
;
return
;
}/*
*
de:
* Reservieren der ersten Verbindung der Datenbank im
Vector um zu prüfen ob eine
* Datenbankverbindung
erstellt werden kann.
* en:
* Reserve the first
database-connection in the Vector to check if a database-connection
* can be established. */
int
locintDBConnectionReference
= reserveConnection(
this
,
true
);
if
(
locintDBConnectionReference < 0)
return
;
Connection
locDBConnection = getReservedConnection(this
,
locintDBConnectionReference);
returnReservedConnection(this
,
locintDBConnectionReference);
}/*
* METHODEN
/ METHODS
* -------------------- *//*
*
de:
* METHODE zum 'Reservieren' einer Verbindung.
*
Zuerst wird geprüft, ob eine unbenutzte Verbindung (zur
Datenbank) bereits innerhalb
* des Vectors existiert.
*
Wenn eine existiert wird sie reserviert (das anfordernde Objekt wird
in vecConnectionUser
* gespeichert);
* um es
später wieder zu finden wird der Index des Vector-Elements
zurück geliefert.
* Wenn keine unbenutzte
Datenbankverbindung gefunden wird wird der Vector um 1 Element
*
erweitert und die neu erstellte Datenbankverbindung wird im neuen
Element gespeichert.
* en:
* METHOD to 'reserve' a
connection.
* First, it is checked if there is an
unused connection (to the database)
* available within
the vector.
* If there is one, then it is reserved (the
requesting object is stored in the vecConnectionUser);
* to
find it later, the index of the vector-element is returned.
* If
there is no unused connection, the vector is extended by 1 element
and the
* newly established database-connection is
stored in the new element. */
public
synchronized int
reserveConnection(Object
parmRequestedFromClass,
boolean
parmReadOnly)
{
/*
*
de:
* Variable für die Datenbankverbindung; wird
gebracht wenn eine DB-Verbindung neu erstellt werden muss.
*
en:
* Variable for database-connection; needed if a new
DB-connection has to be established. */
Connection
conDBConnection =
null
;
/*
*
de: Zurück setzen des Status-Codes und der Status-Nachricht
*
en: Reset the Status-Code and the Status-Message. */
StatusCode
=
CONST_STATUS_OK
;
StatusMsg
=
""
;
/*
*
de: Prüfen ob eine unbenutzte Verbindung verfügbar ist.
*
en: Check if there is an unused connection available. */
int
locintVectorSize
=
vecEstablishedConnections
.size();
int
locintVectorIndex;
Object
classInVector;/* */
for
(locintVectorIndex
= 0; locintVectorIndex < locintVectorSize; locintVectorIndex++)
{
classInVector =
(Object) vecConnectionUsers
.elementAt(locintVectorIndex);
if
(classInVector
==
null
)
{
/*
*
de:
* Unbenutzte Verbindung gefunden.
* Das
'null'-Objekt durch das Objekt, dass die Verbindung angefordert hat,
ersetzen.
* Das markiert die Verbindung als 'verwendet'.
*
en:
* Found an unused connection.
* Change the
null-object against the object that requests the connection.
* This
marks the connection as 'used'.
*/
vecConnectionUsers
.setElementAt(parmRequestedFromClass,
locintVectorIndex);
/*
*
de:
* 'AutoCommit' setzen wenn der 'ReadOnly' Parameter
übergeben wird.
* Mit AutoCommit kann der
Rollback-Buffer besser verwaltet werden und das erhöht die
Performanz.
* en:
* Set the 'AutoCommit' if the
'ReadOnly'-parameter is passed.
* With AutoCommit the
rollback-buffer can be managed more efficient and that increases
performance. */
conDBConnection
= (Connection)
vecEstablishedConnections
.elementAt(locintVectorIndex);
try
{
if
(parmReadOnly)
conDBConnection.setAutoCommit(
true
);
else
conDBConnection.setAutoCommit(
false
);
}
catch
(SQLException
SQLExc) {
StatusCode
=
CONST_DATABASE_CONNECTION_BROKE
;
StatusMsg
=
SQLExc.getMessage();
return
-1;
}/*
*
de:
* Esistierende unbenutzte Datenbankverbindung wurde als
'benutzt' markiert;
* Index des Vector-Elements als
'Reservierung-Nummer' zurück liefern.
* en:
*
Existing unused database-connection marked as used;
* return index
of the vector-Element as 'reservation-number'. */
return
locintVectorIndex;
}
}/*
*
de:
* Keine unbenutzte Verbindung innerhalb des Vectors
gefunden.
* Eine neue Datenbankverbindung eröffnen und
in einem Vector-Erlement registrieren.
* en:
* No
unused connection found within the vector.
* Open a
new database-connection and register it at a
vector-element. */
/*
* de:
*
Zuerst prüfen ob die XML-Struktur mit den Parametern für
die Datenbankverbindung
* alle Parameter enthällt.
*
en:
* First check if the XML-structure with the
DB-connection-parameters
* covers all
parameters. */
String
locstrDataBaseDriverName =
structJSBS_XML_Connections
.getDataBaseDriverName();
if
(locstrDataBaseDriverName
==
null
)
{
StatusCode
=
CONST_DATABASEDRIVERNAME_ELEMENT_MISSING
;
return
-1;
}/*
*/
String
locstrDataBaseName =
structJSBS_XML_Connections
.getDataBaseName();
if
(locstrDataBaseName
==
null
)
{
StatusCode
=
CONST_DATABASENAME_ELEMENT_MISSING
;
return
-1;
}/*
*/
String
locstrDataBaseUserID =
structJSBS_XML_Connections
.getDataBaseUserID();
if
(
locstrDataBaseUserID ==
null
)
{
StatusCode
=
CONST_DATABASEUSERID_ELEMENT_MISSING
;
return
-1;
}/*
*/
String
locstrDataBasePassword =
structJSBS_XML_Connections
.getDataBasePassword();
if
(locstrDataBasePassword
==
null
)
{
StatusCode
=
CONST_DATABASEPASSWORD_ELEMENT_MISSING
;
return
-1;
}/*
*
de: Klasse mit dem Treiber für die Verbindung zur Datenbank
laden.
* en: Load the class with the database-driver
*/
try
{
Class.forName(locstrDataBaseDriverName);
}
catch
(Exception
e) {
StatusCode
=
CONST_DATABASEDRIVER_LOAD_FAILED
;
StatusMsg
=
"Error
while loading class for database-driver: "
+
locstrDataBaseDriverName;
return
-1;
}/*
*
de: Verbindung zur Datenbank erstellen.
* en: Establish
the connection to the database */
try
{
conDBConnection
=
DriverManager.getConnection(locstrDataBaseName,
locstrDataBaseUserID,
locstrDataBasePassword);
}
catch
(Exception
e) {
StatusCode
=
CONST_DATABASE_CONNECTION_FAILED
;
StatusMsg
=
"Error
while establishing database connection for: "
+
locstrDataBaseName
+ ",
"
+
locstrDataBaseUserID
+ ",
"
+
locstrDataBasePassword;
return
-1;
}/*
*
de:
* 'AutoCommit' setzen wenn der 'ReadOnly' Parameter
übergeben wird.
* Mit AutoCommit kann der
Rollback-Buffer besser verwaltet werden und das erhöht die
Performanz.
* en:
* Set the 'AutoCommit' if the
'ReadOnly'-parameter is passed.
* With AutoCommit the
rollback-buffer can be managed more efficient and that increases
performance. */
try
{
if
(parmReadOnly)
conDBConnection.setAutoCommit(
true
);
else
conDBConnection.setAutoCommit(
false
);
}
catch
(SQLException
SQLExc) {
StatusCode
=
CONST_DATABASE_CONNECTION_BROKE
;
StatusMsg
=
SQLExc.getMessage();
return
-1;
}/*
*
de:
* Neue Datenbankverbindung erstellt; in die neuen
Elemente der Vectors eintragen.
* en:
* New
database-connection established; add it in the new elements of the
vectors
*/
vecEstablishedConnections
.addElement(conDBConnection);
vecConnectionUsers
.addElement(parmRequestedFromClass);
StatusCode
=
CONST_STATUS_OK
;
return
(
vecEstablishedConnections
.size()
- 1);
}/*
*
de:
* METHODE um den Zugriff auf eine vorher reservierte
Datenbankverbindung zu erhalten.
* Dabei ist eine
Querprüfung vorgesehen ob das anfordernde Objekt das selbe ist
wie
* das Objekt, das die Verbindung zuvor reserviert
hat.
* Damit wird eine versehentliche falsche Verwendung von
Verbindungen verhindert.
* en:
*
METHOD to get the handle to a previously reserved
database-connection.
* There is a cross-check
implemented that the requesting object is the same
* as
the one that reserved the connection.
* This is to
prevent an erratically miss-assigning of connections. */
public
synchronized
Connection
getReservedConnection(Object
parmRequestedFromClass,
int
parmConnectionReference)
{
/*
*
de: Status-Code zurück setzen.
*
en: Reset the Status-Code. */
StatusCode
=
CONST_STATUS_OK
;
/*
*
de: Prüfen ob die Referenznumber mit der Größe des
Vectors überein stimmt.
*
en: Check if the reference-number fits within the size of the vector.
*/
if
( (parmConnectionReference
< 0)
|| (parmConnectionReference
> (vecEstablishedConnections
.size()
-1))) {
StatusCode
=
CONST_INVALID_REFERENCE
;
return
null
;
}/*
*
de: Prüfen ob das Objekt, das die Verbindung reserviert hat es
jetzt wieder anfordert.
*
en: Check if the object which reserved the connection is requesting
it now. */
if
(parmRequestedFromClass.equals((Object)
vecConnectionUsers
.elementAt(parmConnectionReference)))
{
Connection
conDBConnection =
(Connection)
vecEstablishedConnections
.elementAt(parmConnectionReference);
StatusCode
=
CONST_STATUS_OK
;
return
conDBConnection;
}
else
{
/*
*
de:
* Diskrepanz zwischen dem Objekt, das die Verbindung
reserviert hat und dem Objekt, das sie jetzt anfordert.
*
en:
*
Mismatch
between the object which reserved the connection and object which
requests it now. */
StatusCode
=
CONST_CLASS_MISSMATCH
;
return
null
;
}
}/*
*
de:
* METHODE zum 'retournieren' der Verbindung einer zuvor
reservierten Datenbankverbindung.
* Es wird eine Querprüfung
ausgeführt dass das zurück liefernde Objekt das selbe
ist
* als wie das Objekt, das die Verbindung zuvor
reserviert hat.
* Damit wird eine irrtümliche
Falsch-Zuordnung von Datenbankverbindeungen verhindert.
*
en:
*
METHOD to return the access of a previously reserved
database-connection.
* There is a cross-check
implemented that the returning object is the same
* as
the one that reserved the connection.
* This is to
prevent an erratically miss-assigning of connections. */
public
synchronized void
returnReservedConnection(Object
parmRequestedFromClass,
int
parmConnectionReference)
{
/*
*
de: Status-Code zurück setzen
*
en: Reset the Status-Code. */
StatusCode
=
CONST_STATUS_OK
;
/*
*
de: Prüfen ob die Referenznumber mit der Größe des
Vectors überein stimmt.
*
en: Check if the reference-number fits within the size of the vector.
*/
if
( (parmConnectionReference
< 0)
|| (parmConnectionReference
> (vecEstablishedConnections
.size()
-1))) {
StatusCode
=
CONST_INVALID_REFERENCE
;
return
;
}/*
*
de: Prüfen ob die Referenznumber mit der Größe des
Vectors überein stimmt.
*
en: Check if the reference-number fits within the size of the vector.
*/
if
(!
parmRequestedFromClass.equals((Object)
vecConnectionUsers
.elementAt(parmConnectionReference)))
{
/*
*
de:
* Diskrepanz zwischen dem Objekt, das die Verbindung
reserviert hat und dem Objekt das
* sie jetzt wieder
anfordert.
*
en:
*
Mismatch
between object which reserved the connection and object which
requests it now. */
StatusCode
=
CONST_CLASS_MISSMATCH
;
return
;
}
else
{
/*
*
de: Datenbankverbindung schliessen damit die Einträge in die
Datenbank konsistent sind.
*
Close the connection so that the data-relation is consistent.
*/
Connection
conDBConnection =
(Connection)
vecEstablishedConnections
.elementAt(parmConnectionReference);
try
{
/*
*
de:
* Zusätzliche Sicherheitsprüfung ob die
Datenbank-Verbindung bereits in einer verwendenden
* Methode
geschlossen wurde.
* en:
* Additional
safety-check
if the DB-connection was already closed within a method using it.
*/
if
(!
conDBConnection.isClosed()) {;
if
(!
conDBConnection.getAutoCommit()) {
/*
*
de: 'AutoCommit' nicht gewählt; deswegen jetzt noch einen
'Commit' durchführen.
* en: 'AutoCommit'
not chosen; do the commit now.
*/
conDBConnection.commit();
}
conDBConnection.close();
}
}
catch
(SQLException
SQLExc) {
/*
*
de:
* Während des Schließens ist ein Fehler im
Datenbanksystem aufgetreten;
* diesen an die aufrufende
Methode melden.
* en:
* Error
in the database-system occured during close; report it to the calling
method. */
StatusCode
=
CONST_DATABASE_CONNECTION_BROKE
;
StatusMsg
=
SQLExc.getMessage();
return
;
}/*
*
de:
* Wenn die Verbindung das letzte Element im Vector ist
dann wird das Element aus dem Vector entfernt.
* en:
*
If
the connection was the last element within the vector then remove the
vector elements. */
if
(parmConnectionReference
== (
vecEstablishedConnections
.size()
- 1))
{
vecEstablishedConnections
.removeElementAt(parmConnectionReference);
vecConnectionUsers
.removeElementAt(parmConnectionReference);
StatusCode
=
CONST_STATUS_OK
;
return
;
}
else
{
/*
*
de:
* Wenn die Datenbankverbindung nicht das letzte Element
im Vector war
* dann die Datenbankverbindung sofort wieder
eröffnen – das spart Zeit wenn sie wieder verwendet
wird.
* en:
* If
the connection was not the last element within the vector
* then
reopen it immediately – that saves time when it is re-used.
*/
/*
* de: Parameter aus der XML-Struktur
auslesen.
*
en: Get
the parameters out of the XML-structure. */
String
locstrDataBaseDriverName =
structJSBS_XML_Connections
.getDataBaseDriverName();
String
locstrDataBaseName =
structJSBS_XML_Connections
.getDataBaseName();
String
locstrDataBaseUserID =
structJSBS_XML_Connections
.getDataBaseUserID();
String
locstrDataBasePassword =
structJSBS_XML_Connections
.getDataBasePassword();
/*
* de:
Klassen mit dem Datenbank-Treiber laden.
*
en: Load
the class with the database-driver */
try
{
Class.forName(locstrDataBaseDriverName);
}
catch
(Exception
e) {
StatusCode
=
CONST_DATABASEDRIVER_LOAD_FAILED
;
StatusMsg
=
"Error
while loading class for database-driver: "
+
locstrDataBaseDriverName;
return
;
}/*
* de:
Verbindung zur Datenbank herstellen.
*
en: Establish
the connection to the database */
try
{
conDBConnection
=
DriverManager.getConnection(locstrDataBaseName,
locstrDataBaseUserID,
locstrDataBasePassword);
conDBConnection.setAutoCommit(
false
);
}
catch
(Exception
e) {
StatusCode
=
CONST_DATABASE_CONNECTION_FAILED
;
StatusMsg
=
"Error
while establishing database connection for: "
+
locstrDataBaseName
+ ",
"
+
locstrDataBaseUserID
+ ",
"
+
locstrDataBasePassword
+ ";
"
+
e.getMessage();
return
;
}/*
*
de: Verbindung als unbenutzt markieren; dazu im 'user'(-Objekt)
'null' eintragen.
*
en: Mark the connection as unused by setting the user(-object) to
'null'. */
vecConnectionUsers
.setElementAt(
null
,
parmConnectionReference);
StatusCode
=
CONST_STATUS_OK
;
return
;
}
}
}}
xxx
Dokument |
Inhalt |
Dieser
Leitfaden enthält die notwendigen Tätigkeiten für
die Entwicklung eines StartFrame (auch als Command-Center
bekannt). |