Sie sind auf Seite 1von 8

JDBC

INTRODUCTION
HOW DOES JDBC WORK
DETAILS ABOUT JDBC
HOW TO SET UP AN ACCESS DATABASE IN WINDOWS
A JDBC EXAMPLE
SQL
Introduction
In today's world the majority of computer programs need some kind of database
connectivity. So a computer language can't be taught as a serious computer language
without any database connectivity. JDB is Java's answer to database connectivity for a
Java application or applet. JDB is a database !"I and a part of Java #nterprise !"Is
from JavaSoft. $%emote &ethod Invocation %&I is also part of the Java #nterprise !"Is'
JDB is in fact very closely related with &icrosoft's Open Database Connectivity
$(DB'. JavaSoft introduced the JDB specification in &arch )**+.
,or more information about JDB check out http-..java.sun.com.products.jdbc.
How do! JDBC wor"
JDB defines a set of !"I objects and methods to interact with the underlying database.
! Java program first opens a connection to the database/ makes a statement object/ passes
S01 statements to the underlying database management system $DB&S' through the
statement object and retrieve the results as well as information about the result set.
#2ample-
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbcodbc!tudentD""#"user"#"$ass%");
!tatement stm=con.create!tatment();
!tring &uer'="select name#class from student";
(esult!et res=stm.e)ecute*uer'(&uer');
%+ile(res.ne)t()) ,
!'stem.out.$rint(res.get!tring(-));
!'stem.out.$rint(".t");
!'stem.out.$rintln(res.get!tring(/));
0
So the line Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); loads the JDB
driver and register it with the Driver&anager. 3he getonnection returns a Java
connection object/ this methods first parameter is a database url. 3he url is of form
jdbc:<subprotocol>:<subname related to the DBMS/Protocol>. 3he getonnection
makes the connection using the driver registered to the subprotocol. Some subprotocol-
odbc the (DB bridge
db4 the IB& DB4 database
So when you have the connection you can create statements/ the connection can stay
open through the lifetime of an application. 5ou get a Statement object by calling the
createStatment/ from the connection object. 6ow when you have a statement object you
can make 7ueries $S#1#3' by calling e2ecute0uery or e2ecute8pdate/ that e2ecute a
S01 I6S#%3/ 8"D!3# or D#1#3# statement. 3he e2ecute0uery method returns a
%esultSet object that provides access to a table of data generated by e2ecuting a
Statement. 5ou can loop trough all rows in the %esultSet with the ne2t method/ this
returns false when there is no more rows in the %esultSet. 3he most important thing with
statements and resultsets is that only one %esultSet per Statement can be open at any
point in time. 3herefore/ if the reading of one %esultSet is interleaved with the
reading of another/ each must have been generated by different Statements. !ll statement
e2ecute methods implicitly close a statment's current %esultSet if an open one e2ists.
Dt#i$! #%out JDBC
3he JDB !"I is in the package java.s7l it consists of 9 interfaces/ + classes and :
e2ceptions in JD;).).
Interfaces-
allableStatement
onnection
Database&etaData
Driver
"reparedStatement
%esultSet
%esultSet&etaData
Statement
lasses-
Date
Driver&anager
Driver"ropertyInfo
3ime
3imestamp
3ypes
#2ceptions-
Data3runcation
S01#2ception
S01<arning
3he most important ones are Driver&anager/ onnection/ Statement/ %esultSet.
3he first thing is to register the JDB driver with the Driver&anager. 3he most common
way to do this is to load the class by the class name like
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); this loads the JDB=(DB bridge
from JavaSoft and Intersolv. 3he JDB=(DB Bridge is part of the JDB distribution.
3his loads the IB& DB4 database application JDB D%I>#%-
lass.for6ame$?(&.ibm.db4.jdbc.app.DB4Driver?'@
!nd this the IB& DB4 network JDB D%I>#%-
lass.for6ame$?(&.ibm.db4.jdbc.net.DB4Driver?'@
!s you see vendors can make different drivers depending how the applications will
communicate. 3he JDB driver can also be in a native module/ for windows the JDB=
(DB bridge is in a native module named jdbcodbc.dll.
How to !t u& #n Acc!! d#t#%#! in window!
3his will show you how to make a Java application using a &icrosoft !ccess database.
Indeed !ccess is not a good database system but it's easy to use/ widely spread in home
computers and cheap. If you make a real application/ an application that is in commercial
use/ I strongly suggest that you use some of the big database system like (racle or DB4.
So start !ccess and choose a name for the database
&ake the tables and columns with the A8I
(pen the windows ontrol "anel and click the icon (DB
lick the !dd button
hoose the &icrosoft !ccess driver and press ,innish
lick the Select button and browse to the database file you made
Aive the database a name
$(ptional' lick the !dvance button and fill in a user name and password
lick (k
3hatBs it
A JDBC E'#(&$
Cere is simple database called simpledb. Simpledb have : tables named S38D#63S/
(8%S#S and %!6;S. It looks like this-
STUDETS
Studentnr $!uto6umber primary key'
!name $te2t DE'
"name $te2t DE'
#$e $Integer'
Class $Integer'
COU%SES
Coursenr $!uto6umber primary key'
Course $te2t DE'
Cred&t'un&ts $Integer'
%#(S
Studentnr $,oreign key to S38D#63S.studentnr'
Coursenr $,oreign key to (8%S#S.coursenr'
%an) $Integer'
3hen I made a JDB3est applications that look like this-
5ou can fill in all details that JDB needs to know/ to work properly. 3he Driver name/
database url/ username/ password and make 7ueries to the database.
3he code-
im$ort java.s&l.1;
im$ort java.a%t.1;
$ublic class JD"C2est e)tends 3anel,
$rivate 2e)t4ield driver#database#user#$ass#&uer';
$rivate 2e)t5rea field;
$rivate Connection con;
$ublic static void main(!tring arr67) ,
4rame f=ne% 4rame("JD"C 8)am$le");
JD"C2est test=ne% JD"C2est();
f.add(test);
f.$ac9();
f.s+o%();

0
$ublic void connect() ,
tr' ,
if(con:=null)
con.close();
con=DriverManager.getConnection(database.get2e)t()#
user.get2e)t()#
$ass.get2e)t() );
field.set2e)t("Connected");
0catc+ (8)ce$tion e) ,
field.a$$end(e.to!tring());
!'stem.err.$rintln(e.to!tring());
e.$rint!tac92race(!'stem.err);
0
0
$ublic void register() ,
tr' ,
Class.forName(driver.get2e)t());
field.set2e)t("(egistered");
0 catc+ (8)ce$tion e) ,
field.a$$end(e.to!tring());
!'stem.err.$rintln(e.to!tring());
e.$rint!tac92race(!'stem.err);
0
0

$ublic boolean action(8vent evt#Object %+at) ,
if(evt.target instanceof "utton) ,

field.set2e)t("");

if(%+at.to!tring().e&uals("*uer'")) , ;; do a select &uer'
tr' ,
!tatement stm=con.create!tatement();
(esult!et res=stm.e)ecute*uer'(&uer'.get2e)t());
(esult!etMetaData meta=res.getMetaData();
for(int i=-;i<=meta.getColumnCount();i==)
field.a$$end(meta.getColumnName(i)= ".t");
field.a$$end(".n.n");
%+ile(res.ne)t()) ,
for(int i=-;i<=meta.getColumnCount();i==)
field.a$$end(res.get!tring(i)= ".t");
field.a$$end(".n");
0
res.close();
stm.close();
0 catc+ (8)ce$tion e) ,
field.a$$end(e.to!tring());
!'stem.err.$rintln(e.to!tring());
e.$rint!tac92race(!'stem.err);
0
0
else if(%+at.to!tring().e&uals(">$date")) ,
;;do u$date#delete#insert &uer'
tr' ,
!tatement stm=con.create!tatement();
;; t+e e)ecute>$date dosen?t return a (esultat!et
int code=stm.e)ecute>$date(&uer'.get2e)t());
field.a$$end("O9");
stm.close();
0 catc+ (8)ce$tion e) ,
field.a$$end(e.to!tring());
!'stem.err.$rintln(e.to!tring());
e.$rint!tac92race(!'stem.err);
0
0
else if(%+at.to!tring().e&uals("Connect"))
connect();
else if(%+at.to!tring().e&uals(">$date driver"))
register();
0
return true;
0
$ublic JD"C2est() ,
set@a'out(ne% "order@a'out());
3anel to$=ne% 3anel();
to$.set@a'out( ne% Arid@a'out(B#-) );
3anel ro%=ne% 3anel();
ro%.add(ne% @abel("Driver") );
driver=ne% 2e)t4ield("sun.jdbc.odbc.JdbcOdbcDriver"#CD);
ro%.add(driver);
ro%.add(ne% "utton(">$date driver"));
to$.add(ro%);

ro%=ne% 3anel();
ro%.add(ne% @abel("Database url") );
database=ne% 2e)t4ield(CD);
ro%.add(database);
ro%.add(ne% "utton("Connect"));
to$.add(ro%);

ro%=ne% 3anel();
ro%.add(ne% @abel("user") );
user=ne% 2e)t4ield(CD);
ro%.add(user);
to$.add(ro%);

ro%=ne% 3anel();
ro%.add(ne% @abel("$ass%ord") );
$ass=ne% 2e)t4ield(CD);
ro%.add($ass);
to$.add(ro%);
3anel mid=ne% 3anel();
mid.set@a'out(ne% 4lo%@a'out() );
mid.add(ne% @abel("*uer'") );
&uer'=ne% 2e)t4ield(-DD);
mid.add(&uer');
mid.add(ne% @abel());
mid.add(ne% "utton("*uer'"));
mid.add(ne% "utton(">$date"));

3anel bot=ne% 3anel();
bot.set@a'out(ne% 4lo%@a'out() );
bot.add(ne% @abel("(esult") );
field=ne% 2e)t5rea();
bot.add(field);


add(to$#"Nort+");
add(mid#"!out+");
add(bot#"Center");
0
0
So lets populate the database. 3he application automatically set the driver to
sun.jdbc.odbc.Jdbc(dbcDriver. 3he database url looks like jdbc-odbc-simpledb.
If we write the s7l statement insert into students (fname , lname , age , class) values
('alle' , '!r"n#vist' , $% , &) .If the transaction is successful the word (k should appear
in the %esult te2t area. 6ow if we write the statement select ' from students the result
3e2t!rea should show-
studentnr fname lname age class
$ alle !r"n#vist $% &
onsider we do these S01 statements-
insert into students (fname , lname , age , class) values (' >ille' , ' Johansson' , 4E , :)
insert into students (fname , lname , age , class) values (' Johan' , ' 1ind7vist' , 4) , 4)
insert into courses (Course , Credit(units) values ('Java )dv' , &)
insert into courses (Course , Credit(units) values ('Java' , &)
select ' from students
studentnr fname lname age class
$ alle !r"n#vist $% &
& *ille Jo+ansson &, -
- Jo+an .ind/vist &$ &
select ' from courses
Coursenr CourseCredit(units
$ Java )dv &
& Java &
insert into ran#s (studentnr , coursenr , ran#) values ($,$,0)
insert into ran#s (studentnr , coursenr , ran#) values ($,&,1)
insert into ran#s (studentnr , coursenr , ran#) values (&,$,-)
insert into ran#s (studentnr , coursenr , ran#) values (&,&,-)
insert into ran#s (studentnr , coursenr , ran#) values (-,$,0)
insert into ran#s (studentnr , coursenr , ran#) values (-,&,0)
So what if we want to find out how >ille Johansson's result is in the Java !dv courseF
2elect lname,fname,course,ran# from students 2,courses C,ran#s 3 4+ere
lname5'Jo+ansson' and fname5'*ille' and course5'Java )dv' and
2.studentnr53.studentnr and C.coursenr53.coursenr
%esult-
lname fname course ran#
Jo+ansson *ille Java )dv -
SQL
1ook in the te2t file S01,!0.t2t for basic S01.

Das könnte Ihnen auch gefallen