Datenbankprogrammierung

Transcrição

Datenbankprogrammierung
Datenbank- und Informationssysteme
Datenbankprogrammierung
Inhaltsverzeichnis:
Inhaltsverzeichnis: Kapitel
Kapitel 77
u
7.1 Embedded SQL
l
l
l
u
7.1 Em
bedded
SQL
DBC
7.2 O
7.2 ODBC
l
l
l
u
7.1.1 Einführung, Precompiler
7.1.2 Programmierung (DCL, EXEC SQL, Cursor)
7.1.3 Dynamic SQL
7.2.1 Konzept, Architektur
7.2.3 Programmierung (Datenpflege, Metadaten)
7.2.3 ODBC V.3.0
7.3 JDBC
7.3 JDBC
l
l
l
7.3.1 Einführung, Architektur
7.3.2-3 Programmierung (Datenpflege, Metadaten)
7.3.4 JDBC 2.0 API
Datenbank- und Informationssysteme
Bild 7 -1
© Sep-02 Prof. Dr. F. Laux
7.1
7.1 Embedded
Embedded SQL
SQL
u
Ermöglicht Zugriff auf Datenbank aus einem
Anwendungsprogramm
l
l
u
Datenbankzugriff in SQL-Syntax
l
l
u
inkompatible Datentypen (impedance mismatch)
Im ANSI SQL Standard enthalten
l
Bild 7 -2
keine Spracherweiterung
Precompiler erforderlich
Datentypanpassung zwischen SQL und Hostsprache
l
u
Erweiterung der Möglichkeiten von SQL durch Programmiersprache
Verbindung des Datenbanksystems zu anderen SW-Systemen
trotzdem herstellerspezifische Erweiterungen
Datenbank- und Informationssysteme
© Sep-2002, F. Laux, Wirtschaftsinformatik, FH Reutlingen
© Sep-02 Prof. Dr. F. Laux
7-1
Datenbankprogrammierung
Datenbank- und Informationssysteme
7.1.1
7.1.1 Übersetzung
Übersetzung
C-Programm mit
embedded SQL
Fehlerprotokoll
embedded SQL
Precompiler
C-Programm mit
API-Calls (SQL-Lib)
C Fehlermeldungen
C-Compiler
Relokatives
Objektprogramm
Standardbibliothek
Lader/Binder
Ausführbares
Anwendungsprogramm
Datenbankbibliothek
(SQL-Lib)
Datenbank- und Informationssysteme
Bild 7 -3
© Sep-02 Prof. Dr. F. Laux
7.1.2
7.1.2 Minimalprogramm
Minimalprogramm
u
Declare Section
EXEC SQL BEGIN DECLARE SECTION;
DCL* persno decimal(6);
DCL ename char(20);
DCL server char(20);
DCL userid char(20);
DCL passwd char(20);
EXEC SQL END DECLARE SECTION;
*Syntax ist abhängig von der Hostsprache (Cobol: {01|77}; PL/1: DCL; C, Fortran: entfällt)
u
Verbindung herstellen
EXEC SQL CONNECT TO :server
USER :userid [USING :passwd];*
*Syntax variiert je nach DB-System
u
u
SQL-Statement erzeugen
und ausführen
EXEC SQL SELECT Ename INTO :ename
Datenbank schließen
DBCLOSE();
FROM Emp WHERE Persno = :persno;
MinimalProgramm
emb.SQL
Bild 7 -4
Datenbank- und Informationssysteme
© Sep-2002, F. Laux, Wirtschaftsinformatik, FH Reutlingen
© Sep-02 Prof. Dr. F. Laux
7-2
Datenbankprogrammierung
Datenbank- und Informationssysteme
7.1.2
7.1.2 SQL
SQL Declare
Declare Section,
Section, SQLCA
SQLCA
Kommentare/Beispiele
u
Begrenzer für Declare Section
l
l
u
u
Definition von Host Variablen
l
<host_var> <SQL-Type>;
l
EXEC SQL INCLUDE SQLCA
EXEC SQL und ; ist Markierung
für Precompiler
SQLCA
persno decimal(6);
Kommunikationsbereich für FehlerMeldungen
emb.SQL
Deklaration von Tabellen
l
u
EXEC SQL BEGIN DECLARE SECTION;
EXEC SQL END DECLARE SECTION ;
EXEC SQL DECLARE <tab> TABLE ( <attrDecl_list>);
bei Oracle von Generator erzeugt
Definition von Cursors
l
EXEC SQL DECLARE <curs> CURSOR FOR
<SELECT-Clause>
DECLARE <curs> CURSOR FOR
select persno, ename from emp
where deptid = :deptid;
Datenbank- und Informationssysteme
Bild 7 -5
© Sep-02 Prof. Dr. F. Laux
7.1.2
7.1.2 Single
Single Result
Result Operation
Operation
Kommentare/Beispiele
u
Insert/ Update/ Delete
l
EXEC SQL INSERT INTO emp
EXEC SQL
<SQL_insert/update/delete_stmt> ;
VALUES (:persno, :ename);
EXEC SQL UPDATE emp SET
ename = :ename WHERE <cond>;
EXEC SQL DELETE FROM emp
WHERE persno =:persno;
u
Single Row Query
l
Bild 7 -6
EXEC SQL
SELECT <attr_list> INTO <hostVar_list >
EXEC SQL
SELECT ename INTO :ename
FROM <tab> WHERE <1row_cond> ;
FROM emp WHERE persno = :persno;
Datenbank- und Informationssysteme
© Sep-2002, F. Laux, Wirtschaftsinformatik, FH Reutlingen
© Sep-02 Prof. Dr. F. Laux
7-3
Datenbankprogrammierung
Datenbank- und Informationssysteme
7.1.2
7.1.2 Multirow
Multirow Query,
Query, Cursor
Cursor
Kommentare/Beispiele
u
Cursor deklarieren
l
u
OPEN <curs> ;
OPEN nyEmp ;
Ergebnisse in Schleife verarbeiten
l
u
DECLARE nyEmp CURSOR FOR
select persno, ename from emp
where deptid = :deptid ;
Cursor öffnen (Query ausführen)
l
u
DECLARE <curs> CURSOR FOR <select_stmt>
[FOR UPDATE OF <attrib_list> ;
FETCH <curs> INTO <hostVar_list>
Cursor schließen
Multirow
Query
CLOSE <curs>
emb.SQL
l
while (sqlcode == 0) {
FETCH nyEmp into :persno, :ename;
... }
/* sqlcode == +100 no data,
> 0 Warning, < 0 Error */
Datenbank- und Informationssysteme
Bild 7 -7
© Sep-02 Prof. Dr. F. Laux
7.1.2
7.1.2 Fehlerbehandlung
Fehlerbehandlung
u
Explizite Fehlerabfrage durch
l
l
u
SQLCODE
SQLSTATE
(= 0 ok, +100 keine Daten, < 0 Error, > 0 Warning)
(= ccuuu, cc = 2-stelliger Klassenwert z.B. 00 = successful completion,
01 = warning, 02 = no data found, 07 = dyn. SQL-Err.
08 = connection error, 0A = feature not supported, ...)
uuu = 3-stelliger Unterklassenwert z.B. bei cc = 01, kann
uuu = 003 (NULLs in Aggregat-Fkt. Ignoriert),
uuu = 006 (Privilege not revoked) sein
Implizite Fehlerabfrage durch
Bild 7 -8
l
WHENEVER {NOT FOUND | SQLWARNING | SQLERROR} {CONTINUE | <goto_stmt>}
l
Precompiler erzeugt Fehlerabfrage für jede SQL-Anweisung und verzweigt zur
angegebenen Sprungmarke
Datenbank- und Informationssysteme
© Sep-2002, F. Laux, Wirtschaftsinformatik, FH Reutlingen
© Sep-02 Prof. Dr. F. Laux
7-4
Datenbank- und Informationssysteme
Datenbankprogrammierung
7.1.3
7.1.3 Dynamic
Dynamic SQL
SQL 92
92 (1)
(1)
u
u
u
SQL-Anweisung ist erst zur Laufzeit bekannt
Metainformation über SQL Description Area (SQLDA) erfragen
Dynamic SQL Übersicht (Methode 4)
EXEX SQL ...
l INCLUDE SQLDA;
l
Declare Hostvariable für <SQL_stmt>;
DECLARE <stmt_name> STATEMENT;
<SQL_stmt> = "SQL String";
PREPARE <stmt_ prepName > FROM <SQL_stmt>;
ALLOCATE DESCRIPTOR <descr> [WITH MAX <anzahl> ];
l
DESCRIBE {INPUT | OUTPUT} <stmt_prepName> USING SQL DESCRIPTOR <descr>;
l
Input gibt Infos über die Eingabeparameter
Output gibt Infos über das Ergebnis (z.B. Attributtypen)
EXECUTE <stmt_prepName> [INTO <outHostVar_list> ] [USING <inHostVar_list> ];
DECLARE <curs> [INSENSITIVE] [SCROLL] CURSOR FOR <stmt_prepName>;
FETCH <curs> INTO <outHostVar_list>;
l
l
l
l
Dyn.SQL
Method 4
emb.SQL
l
l
l
l
Datenbank- und Informationssysteme
Bild 7 -9
© Sep-02 Prof. Dr. F. Laux
7.1.3
7.1.3 Dynamic
Dynamic SQL
SQL 92
92 (SQLDA)
(SQLDA)
u SQL
u
u
u
u
u
Descriptor Area (SQLDA) Struktur
SQLDAID
Name des Deskriptors
SQLDALEN
Größe des Deskriptors
SQLN
Anzahl der Einträge in SQLVAR
SQLTYPE
Typ der SQL Anweisung
SQLVAR
Array[1 .. SQLN]
mit den Einträgen (Struktur) für jedes Attribut:
l
l
l
l
Bild 7 -10
SQLNAME
SQLTYPE
SQLLEN
SQLDATA
Name Attributs
Datentyp Attributs
Länge des Attributs
Verweis auf Attributwert
Datenbank- und Informationssysteme
© Sep-2002, F. Laux, Wirtschaftsinformatik, FH Reutlingen
Oracle
SQLDA
emb.SQL
© Sep-02 Prof. Dr. F. Laux
7-5
Datenbankprogrammierung
Datenbank- und Informationssysteme
7.2
7.2 ODBC
ODBC
u
Einheitliches API für den Datenzugriff auf verschiedene Datenquellen
l
l
l
u
Implementierung des Call Level Interface (CLI) der X/Open Gruppe
l
l
l
u
X/Open = Zusammenschluß von DBMS-Herstellern
Komponente von MS Data Access (MDAC)
Unterstützung durch ANSI und ISO
Systemneutral
l
l
u
relationale Datenbanken
nichtrelationale Datenbanken
Dateien
Einsatz unter verschiedenen Betriebssystemen
Unterstützung durch verschiedene Programmiersprachen
unterstützt Client/Server-Architektur
l
l
Bild 7 -11
Client = Anwendung und ODBC-Treiber
Server = lokale oder entfernte Datenquelle
Datenbank- und Informationssysteme
© Sep-02 Prof. Dr. F. Laux
7.2.1
7.2.1 Architektur
Architektur
Anwendung
ODBC
ODBCTreiber-Manager
Treiber-Manager
Ein-Stufen
Ein-StufenTreiber
Treiber
Datei I/O
DBMSAPI
Datenquelle
A (lokal)
Client
Zwei-Stufen
Zwei-StufenTreiber
Treiber
DBMS-API
DBMS-API
Netzprotokoll/RPC
Netzprotokoll/RPC
Netz-/RPCprotokoll
Datenquelle
B
Server
Bild 7 -12
Datenbank- und Informationssysteme
© Sep-2002, F. Laux, Wirtschaftsinformatik, FH Reutlingen
© Sep-02 Prof. Dr. F. Laux
7-6
Datenbank- und Informationssysteme
Datenbankprogrammierung
7.2.1
7.2.1 Minimalprogramm
Minimalprogramm
u
Variablen definieren
u
Handles allokieren
u
u
Verbindung herstellen
Statement erstellen
und ausführen
Ergebnis auslesen
u
Ressourcen freigeben
u
MinimalProgramm
signed short rc;
/* return code RETCODE */
void far * henv, hdbc, hstmt;
/* handles */
SQLAllocEnv(&henv);
SQLAllocConnection(henv, &hdbc);
SQLConnect(hdbc, "<dataSrc>", ....);
SQLAllocStmt(hdbc, &hstmt);
SQLExecDirect(hstmt, "select * from ... ", ...);
rc = SQLFetch(hstmt);
if (rc == SQL_SUCCESS)
SQLGetData(hstmt, colno, SQL_C_CHAR,
szData, sizeof(szData), &actLen);
SQLFreeStmt(hstmt, SQL_DROP);
SQLDisconnect(hdbc); SQLFreeConnect(hdbc);
SQLFreeEnv(henv);
ODBC
Datenbank- und Informationssysteme
Bild 7 -13
© Sep-02 Prof. Dr. F. Laux
7.2.2
7.2.2 SQLBindCol,
SQLBindCol, SQLBindParmeter
SQLBindParmeter
u
Zuordnung von Datenbankwerten einer Programmvariablen
l
u
Zuordnung von Parameterwerten einer Programmvariablen
l
u
SQLBindCol(<hstmt>, <colno>, <C-type>, <var>, <var-len>, &<actlen>);
SQLBindParameter(<hstmt>, <pno>, <I/O-ptype>, <C-type>, <SQL-type>,
<coldef>, <scale>, <var>, <var-len>, &<actlen>);
Beispiel
l
l
l
l
l
l
l
l
Bild 7 -14
SQLBindCol(hstmt, 1, SQL_C_CHAR, f1, MAX_DATA, &cbData1);
SQLBindCol(hstmt, 2, SQL_C_LONG, &lf2, sizeof(lf2), &cbData2);
SQLExecDirect(hstmt, "select * from Tab1", SQL_NTS);
SQLFetch(hstmt); /* füllt Variablen f1 und lf2 */
SQLExecDirect(hstmt2, "create table Tab2 (f1 text(255), f2 long)",SQL_NTS);
SQLBindParameter(hstmt2, 1, SQL_PARAM_INPUT, SQL_C_CHAR,
SQL_CHAR, 255, 0, f1, sizeof(f1), &cbData1);
SQLBindParameter(hstmt2, 2, SQL_PARAM_INPUT, SQL_C_LONG,
SQL_INTEGER, 0, 0, &lf2, sizeof(lf2),&cbData2);
SQLExecDirect(hstmt2, "insert into Tab2(f1, f2) values (?,?)", SQL_NTS);
Datenbank- und Informationssysteme
© Sep-2002, F. Laux, Wirtschaftsinformatik, FH Reutlingen
Programm
(BindCol/Param)
ODBC
© Sep-02 Prof. Dr. F. Laux
7-7
Datenbank- und Informationssysteme
Datenbankprogrammierung
7.2.2
7.2.2 SQLPrepare,
SQLPrepare, SQLExecute
SQLExecute
u
Optimierung der Ausführungszeiten
l
SQLExecDirect versus SQLPrepare und SQLExecute
l
l
l
u
u
u
SQLExecDirect parst SQL-String, erstellt Ausführungsplan und führt Befehl aus
SQLPrepare parst SQL-String und erstellt Ausführungsplan
SQLExecute führt vorbereiteten SQL-Befehl aus
SQLPrepare(<hstmt>, <SQL-string>, <SQL-strType>);
SQLExecute(<hstmt>);
Beispiel
l
l
l
SQLPrepare(hstmt2, "insert into MyFiles(f1, f2, f3, f4) values (?, ?, ?, ?)", SQL_NTS);
rc = SQLExecDirect(hstmt, "select * from MyFiles", SQL_NTS);
for(rowcount = 0, rc = SQLFetch(hstmt); rc == SQL_SUCCESS; rc = SQLFetch(hstmt)) {
SQLExecute(hstmt2);
...;
Programm
};
(Prepare/Execute)
ODBC
Bild 7 -15
Datenbank- und Informationssysteme
© Sep-02 Prof. Dr. F. Laux
7.2.2
7.2.2 ODBC
ODBC Fehlercodes
Fehlercodes
u
u
u
u
u
u
u
#define SQL_INVALID_HANDLE
#define SQL_ERROR
#define SQL_SUCCESS
#define SQL_SUCCESS_WITH_INFO
#define SQL_NO_DATA_FOUND
(-2)
(-1)
0
1
100
#define SQL_STILL_EXECUTING
#define SQL_NEED_DATA
2
99
Bild 7 -16
Datenbank- und Informationssysteme
© Sep-2002, F. Laux, Wirtschaftsinformatik, FH Reutlingen
© Sep-02 Prof. Dr. F. Laux
7-8
Datenbank- und Informationssysteme
Datenbankprogrammierung
7.2.3
7.2.3 ODBC
ODBC 3.0
3.0
u
u
Anpassung an ISO CLI Standard
l
SQLAllocHandle anstatt SQLAllocConnect, ..Stmt, ...
l
Deskriptoren (Metadateninfos)
OLE Datenzugriff
l
l
u
mehrfaches Binden
effizientes binden von variablen Daten
Unterstützung für
l
l
l
l
l
BLOBs,
Parameterarrays,
Fetch-Suche
Aktualisierung einer Ergebnisspalte
nebenläufige SQL-Statements
Datenbank- und Informationssysteme
Bild 7 -17
© Sep-02 Prof. Dr. F. Laux
7.2.3
7.2.3 ODBC
ODBC 3.0
3.0 (Deskriptoren)
(Deskriptoren)
u
Deskriptoren beschreiben
l
l
u
Anwendungsparameter
Treiberparameter
Deskriptorfelder
l
Header
l
Daten
l
l
u
COUNT, ALLOC_TYPE
TYPE, LENGTH, PRECISION, SCALE, NULLABLE, ...
Deskriptorfunktionen
l
l
*
Bild 7 -18
SQLGetDescField
SQLSetDescField
bei Ver. 2.x durch verschieden Funktionen realisiert
(z.B. SQLBindParameter, SQLDescribeCol, SQLGetData, ...)
Datenbank- und Informationssysteme
© Sep-2002, F. Laux, Wirtschaftsinformatik, FH Reutlingen
© Sep-02 Prof. Dr. F. Laux
7-9
Datenbankprogrammierung
Datenbank- und Informationssysteme
7.3
7.3 JDBC
JDBC
u Was
l
l
l
l
ist JDBC ?
Java API zur Ausführung von SQL-Befehlen
Besteht aus Klassen und Schnittstellen, die in Java
geschrieben sind
JDBC ermöglicht DB-Anwendungen, die ausschließlich
in Java geschrieben sind
JDBCTM ist eine Schutzmarke, kein Akronym
Bild 7 -19
Datenbank- und Informationssysteme
© Sep-02 Prof. Dr. F. Laux
7.3.1
7.3.1 JDBC
JDBC Architektur
Architektur
u Client
Java Applikation
Java Applet/
Web-Browser
JDBC-Treiber
HTTP, RMI,
Corba
u Middle
Applikationsserver
Ware
JDBC-Treiber
DB-spezif.
Protokoll
u DB-Server
Bild 7 -20
DB-spezif.
Protokoll
DBMS
Datenbank- und Informationssysteme
© Sep-2002, F. Laux, Wirtschaftsinformatik, FH Reutlingen
© Sep-02 Prof. Dr. F. Laux
7 - 10
Datenbankprogrammierung
Datenbank- und Informationssysteme
7.3.1
7.3.1 Treibertypen
Treibertypen
Java Anwendung
APIs:
JDBC
JDBC Driver Manager
Driver
JDBC-ODBC
Bridge
Java-Wrapper
(z.B. für C)
JDBC NetzTreiber
ODBC
Treiber
DB-Treiber
(z.B. in C)
Middle Ware
(z.B. Corba)
RDBMS x
RDBMS y
Typ 1
Typ2
JDBC Treiber
Treiber/
Netz
RDBMS
RDBMS z
Typ 3
Datenbank- und Informationssysteme
Bild 7 -21
Typ 4
© Sep-02 Prof. Dr. F. Laux
7.3.1
7.3.1 Minimalprogramm
Minimalprogramm
u
JDBC Treiber laden
Class.forName ("path.to.jdbc.Driver");
u
Verbindung aufbauen
Connection conn;
conn = DriverManager.getConnection(url,uid,pwd);
u
SQL-Statement erzeugen
Statement stmt = conn.createStatement();
u
Statement ausführen
ResultSet rs = stmt.executeQuery("select * from ...");
u
Ergebnisse auslesen
while (rs.next())
{"for each attribute-index (i) "
variable(i) = rs.getObject(i);
.. "do something with variable(i) "... }
u
Statement schließen
stmt.close;
u
Verbindung schließen
conn.close;
Bild 7 -22
Datenbank- und Informationssysteme
© Sep-2002, F. Laux, Wirtschaftsinformatik, FH Reutlingen
MinimalProgramm
© Sep-02 Prof. Dr. F. Laux
7 - 11
Datenbankprogrammierung
Datenbank- und Informationssysteme
7.3.2
7.3.2 Verbindung
Verbindung herstellen
herstellen
u
Treiber laden
l
u
Kommentare/Beispiele
Class.forName(“<pfad.fuer>.<JdbcDriver>“);
erzeugt ClassNotFoundException
oracle.thin.JdbcDriver
solid.JdbcDriver
mit DB verbinden
l
URL aufbauen
l
l
String url = “jdbc:<subprotocol>:<subname>“;
jdbc:odbc:myDataSource
jdbc:oracle:thin:@dblabor1/dbName
jdbc:solid://dblabor1.fh-rt.de:1313
verbinden und anmelden
l
Connection conn =
DriverManager.getConnection(
url, “<uid>“, “<pwd>“);
erzeugt SQLException
Datenbank- und Informationssysteme
Bild 7 -23
© Sep-02 Prof. Dr. F. Laux
7.3.2
7.3.2 Tabellen
Tabellen anlegen
anlegen
u
Statement erzeugen
l
u
Kommentare/Beispiele
Statement stmt = conn.createStatement();
erzeugt SQLException
wird für alle Datenbankzugriffe benötigt
Statement ausführen
l
l
mit explizitem String-Objekt
l
String sqlCreate = “create table <table>“ +
“(<col1> <datatype1> <kb1>, ...)“;
l
stmt.executeUpdate(sqlCreate);
SQL-create-table Statement
als String-Objekt
mit implizitem String-Objekt
l
stmt.executeUpdate( “create table <table>“ +
“(<col1> <datatype1> <kb1>, ...)“);
Bild 7 -24
Datenbank- und Informationssysteme
© Sep-2002, F. Laux, Wirtschaftsinformatik, FH Reutlingen
© Sep-02 Prof. Dr. F. Laux
7 - 12
Datenbankprogrammierung
Datenbank- und Informationssysteme
7.3.2
7.3.2 Daten
Daten manipulieren
manipulieren
u
Statement erzeugen (siehe Bild 7-24)
u
Statement ausführen (siehe Bild 7-24 für die Variante mit explizitem String-Objekt)
l
Daten eingeben
l
stmt.executeUpdate( “insert into <table>“ +
“values (<val1>, <val2>, ...)“);
l
Daten ändern
l
stmt.executeUpdate( “update <table>“ +
“set <col1> = <val1>, ...“);
l
Daten löschen
l
stmt.executeUpdate( “delete from <table>“ +
“where <col1> = <val1>, ...“);
Datenbank- und Informationssysteme
Bild 7 -25
© Sep-02 Prof. Dr. F. Laux
7.3.2
7.3.2 Tabellen
Tabellen abfragen
abfragen
u
Statement erzeugen (siehe Bild 7-24)
u
Query ausführen
l
u
Kommentar/Beispiel
ResultSet rs = stmt.executeQuery( "select <col_list>" +
"from <table> where ...");
„ResultSet“ auslesen
l
über getObject
l
l
l
über getInt, getFloat, getString, getDate, getTime,
getAsciiStream, getBinaryStream, ...
l
l
Bild 7 -26
idx = rs.findColumn(“Adresse");
Object obj = rs.getObject(<index>|"<AttrName>") ;
Objekttyp umwandeln (falls geeignet)
var = new <Type>(obj.toString()).<type>Value();
var = rs.getXXX(<index>|"<AttrName>");
if ( var = 0 && rs.wasNull )
Adresse adr = rs.getObject(idx);
fl = new Float(dm.toString()).floatValue();
BLOB stückweise auslesen
fl = rs.getFloat("betrag");
NULL-Marke erkennen !
Bei echten Objekten, kann auf var = NULL
abgefragt werden.
Datenbank- und Informationssysteme
© Sep-2002, F. Laux, Wirtschaftsinformatik, FH Reutlingen
© Sep-02 Prof. Dr. F. Laux
7 - 13
Datenbank- und Informationssysteme
Datenbankprogrammierung
7.3.3
7.3.3 Metadaten
Metadaten („ResultSet“
(„ResultSet“ Infos)
Infos)
u
Verbindung herstellen, Query ausführen (siehe Bild 7-24, 7-26)
u
ResultSet für Metadaten erzeugen
l
u
Spaltenanzahl ermitteln
l
u
int numCols = rsmd.getColumnCount();
Spaltenüberschrift ermitteln
l
u
ResultSetMetaData rsmd = rs.getMetaData();
for (int i = 1; i <= numCols; i++)
{ String colName = rsmd.getColumnLabel(i); ...}
Attributtyp ermitteln
l
l
int colType = rsmd.getColumnType(i); oder
String colTName = rsmd.getColumnTypeName(i);
JDBC- und Java Types siehe Bild 7-36
Datenbank- und Informationssysteme
Bild 7 -27
Metadaten
© Sep-02 Prof. Dr. F. Laux
7.3.3
7.3.3 Metadaten
Metadaten (Datenbank
(Datenbank Infos)
Infos)
u
Verbindung herstellen (siehe Bild 7-24)
u
Metadaten Objekt erzeugen
l
u
DatabaseMetaData dbmd = conn.getMetaData();
Metadaten auslesen
l
DB Produktname und Versionsnummer
l
l
l
Metadaten
Meta-Meta-Daten
l
l
String dbName = dbmd.getDatabaseProductName();
String dbVersion = dbmd.getDatabaseProductVersion();
int maxLength = dbmd.getMaxTableNameLength();
Schema/Kataloginfos
l
ResultSet dbSchema = dbmd.getTables( "<cat>", "<schema>", "<tab>", <types>[]);
liefert eine Tabelle mit den Attributen Table_Cat, Table_Schema, Table_Name, Table_Type,
Remarks, die mit den ResultSet-Methoden auszulesen sind. <cat>, <schema> und <tab> sind
Matchcodes für Katalog-, Schema und Tabellennamen. <types> ist ein Array mit Tabellentypen.
Bild 7 -28
Datenbank- und Informationssysteme
© Sep-2002, F. Laux, Wirtschaftsinformatik, FH Reutlingen
© Sep-02 Prof. Dr. F. Laux
7 - 14
Datenbank- und Informationssysteme
Datenbankprogrammierung
7.3.3
7.3.3 SQL-Exception
SQL-Exception
u
SQLException können bei fast allen JDBC-Klassen auftreten
muss abgefangen werden, da Operation nicht ausgeführt wurde
ist eine von java.lang.Exception abgeleitete Klasse
u
stellt Informationen über Datenzugriffsfehler im catch-Block bereit
u
u
l
l
catch (SQLException ex) {
while (ex != null) {
System.out.println("Java Exception Message: " + ex.getMessage());
System.out.println("SQL State: " + ex.getSQLState());
System.out.println(“vendorspecific code: " + ex.getErrorCode());
ex = ex.getNextException();
}
conn.rollback;
}
SQL State ist ein Fehlercode, der in X/Open SQL Specification definiert ist
Datenbank- und Informationssysteme
Bild 7 -29
© Sep-02 Prof. Dr. F. Laux
7.3.3
7.3.3 SQL-Warning
SQL-Warning
u
SQLWarning können bei Connection, Statement und ResultSet auftreten
unterbricht das Programm nicht
muss mit getWarnings bzw. getNextWarning abgefragt werden
u
stellt Informationen in „besonderen“ Situationen bereit
u
u
l
l
Bild 7 -30
SQLWarning warn = conn.getWarnings();
while (warn != null) {
System.out.println("Java Warning Message: " + warn.getMessage());
System.out.println("SQL State: " + warn.getSQLState());
System.out.println(“Vendorspecific code: " + warn.getErrorCode());
warn = warn.getNextException();
}
SQLWarnings: DataTruncation, Privilege not revoked, Error during
disconnect
Datenbank- und Informationssysteme
© Sep-2002, F. Laux, Wirtschaftsinformatik, FH Reutlingen
© Sep-02 Prof. Dr. F. Laux
7 - 15
Datenbank- und Informationssysteme
Datenbankprogrammierung
7.3.4
7.3.4 JDBC
JDBC 2.0
2.0 API
API Übersicht
Übersicht
Datenbank- und Informationssysteme
Bild 7 -31
© Sep-02 Prof. Dr. F. Laux
7.3.4
7.3.4 Connection,
Connection, DriverManager
DriverManager
u
DriverManager
l
l
u
getConnection(String <url>[, String <usr>, String <pwd>]);
[de]registerDriver(Driver <dvr>)
Connection
l
l
l
l
createStatement(); prepareStatement(String <sql>); prepareCall(String <sql>);
getMetaData();
commit(); rollback();
{set|get}TransactionIsolation(int <level>);
l
l
Bild 7 -32
<level> ∈ { TRANSACTION_SERIALIZABLE, ...REPEATABLE_READ, ...READ_COMMITTED,
..READ_UNCOMMITTED}
setReadOnly(boolean <t/f>); boolean isReadOnly();
Datenbank- und Informationssysteme
© Sep-2002, F. Laux, Wirtschaftsinformatik, FH Reutlingen
© Sep-02 Prof. Dr. F. Laux
7 - 16
Datenbank- und Informationssysteme
Datenbankprogrammierung
7.3.4
7.3.4 Statement
Statement und
und Subklassen
Subklassen
u
Statement
l
l
ResultSet executeQuery(String <sql>); int executeUpdate(String <sql>);
boolean execute(String <sql_script>);
l
l
l
l
u
SQLWarning getWarnings();
{set|get}QueryTimeout(int <sec>); cancel();
PreparedStatement
l
l
u
erzeugt mehrere ResultSets und Update counts. Abgreifen mit:
ResultSet getResultSet(); boolean getMoreResults(); int getUpdateCount();
setXXX(int <parmIdx>, <JavaTypeXXX> <val>);
setNull(int <paramIdx>, int <sqlTypeNo>); clearParameters();
CallableStatement
l
l
l
registerOutParameter(int <paramIdx>, int <sqlType>[, int <scale>]);
<JavaTypeXXX> getXXX(int <parmIdx>);
boolean wasNull();
Datenbank- und Informationssysteme
Bild 7 -33
© Sep-02 Prof. Dr. F. Laux
7.3.4
7.3.4 ResultSet
ResultSet
u
ResultSet
l
l
boolean next(); close();
Nach Spaltennummer
l
Nach Spaltennamen
l
l
<JavaTypeXXX> getXXX(String <colName>);
Object getObject(String <colName>);
l
Als Teilergebnis
l
boolean wasNull();
SQLWarning getWarnings(); clearWarnings();
ResultSetMetaData getMetaData();
int findColumn(String <colName>);
l
l
l
l
Bild 7 -34
<JavaTypeXXX> getXXX(int <colIdx>); Object getObject(int <colIdx>);
InputStream get{ASCII|Unicode|Binary}Stream(String <colName>);
Datenbank- und Informationssysteme
© Sep-2002, F. Laux, Wirtschaftsinformatik, FH Reutlingen
© Sep-02 Prof. Dr. F. Laux
7 - 17
Datenbankprogrammierung
Datenbank- und Informationssysteme
7.3.4
7.3.4 Data
Data Types
Types
u
Java Datatypes
l
u
boolean, byte, double, float, int, long, short, String
Date, Time
l
Date d = new Date(<yy>, <mm>, <dd>); Time t = new Time(<hh>, <mm>, <ss>);
l
valueOf(String "<hh:mm:ss>"); valueOf(String "<yyyy-mm-dd>");
String toString();
l
l
u
yy := Jahr -1900, mm := 0 (Jan.) ... 11 (Dez.)
TimeStamp
l
Timestamp ts = new Timestamp(<yy>, <mm>, <dd>, <hh>, <mm>, <ss>, <ns>);
l
l
l
l
ns := Nanosekunden (1/1000000000sec)
valueOf(String "<yyyy-mm-dd hh:mm:ss.ns>"); String toString();
boolean {after|before|equals}(Timestamp ts);
setNanos(int n); getNanos();
Datenbank- und Informationssysteme
Bild 7 -35
© Sep-02 Prof. Dr. F. Laux
7.3.4
7.3.4 Java
Java vs.
vs. JDBC
JDBC Typen
Typen
Bild 7 -36
Java Typ
JDBC Typ
String
CHAR, VARCHAR,
LONGVARCHAR
java.math.BigDecimal
NUMERIC
boolean
BIT
byte, short, int, long
TINYINT, SMALLINT,
INTEGER, BIGINT
float, double
DEAL, DOUBLE
java.sql.Date, ...Time,
...Timestamp
DATE, TIME, TIMESTAMP
Datenbank- und Informationssysteme
© Sep-2002, F. Laux, Wirtschaftsinformatik, FH Reutlingen
© Sep-02 Prof. Dr. F. Laux
7 - 18
Datenbank- und Informationssysteme
Datenbankprogrammierung
7.3.4
7.3.4 Neue
Neue Funktionen
Funktionen in
in Version
Version 2.0
2.0
u
geordnetes (scrollable) ResultSet
l
u
Stapelverarbeitung (batch updates) im Statement-Objekt
l
l
u
l
u
addBatch(String <sql>);
executeBatch();
Persistente Objekte
l
u
beforeFirst(), next(); relative(int n); afterLast();
ResultSet rs = stmt.executeQuery( “select Mitarbeiter from Personal“);
Mitarbeiter ma = (Mitarbeiter) rs.getObject(1);
Neue Datentypen
l
BLOB, CLOB, Bsp.: Ref ref = rs.getRef(<colIdx));
l
create type Point(x FLOAT, y FLOAT); create type Währung as NUMERIC(10,2);
Namens- und Verzeichnisdienste (JNDI, Java Naming and Directory Interface)
Bild 7 -37
Datenbank- und Informationssysteme
© Sep-2002, F. Laux, Wirtschaftsinformatik, FH Reutlingen
© Sep-02 Prof. Dr. F. Laux
7 - 19

Documentos relacionados