Vous êtes sur la page 1sur 8

JDBC Database Connectivity

JDBC Database Connectivity To utilize the JDBC functionality, one must directly interact with the operating system; thus, there is a certain amount of system configuration that one must complete. The application we develop here presents code to interact with a Microsoft ccess data!ase 1. Creating the Database & DSN Connection Before writing the actual application code, one should first ensure"create the data!ase to !e used. There are really no constraints to which data!ase implementation one can use. #ou can choose any operating system and"or data!ase that support Java technology. The primary difference when using another platform solution is in the way in which the driver and operating system connections are completed. The Java code should not vary e$cept in the string that loads the driver. Creating the Microsoft Access Database The design of your data!ase is %uite simple and represents a small !ase!all e%uipment operation. The data!ase will contain four fields& 'D, (ame, )rice, and *uantity, as illustrated in Ta!le +.
ID 1 2 3 4 Bat Glove Name Baseball Price $2.00 $20.00 $80.00 Quantity 200 20 0

Catchers Glove $100.00 1

Table 1

The a!ove ta!le is created in ccess. To do this, launch Microsoft ccess and create a !lan, data!ase called purchaseOrder.mdb. fter you specify the name of the data!ase as purchase-rder.md!, you then need to create the single ta!le named Transaction that we utilize in this e$ample. fter you enter all of the data in the ta!le you designed, your data!ase should as a!ove. 2. Making the DSN Connection (ow that the data!ase is complete, there is one more step you need to ta,e to ensure the Java application you develop can ma,e a connection to it. This step is highly dependent on the platform that you are using. 'n this e$ample, you need to ma,e a Data .ource name /D.(0 connection to the data!ase. This is the mechanism that allows the application to connect to the data!ase itself.

By:Ritika Wason 1

JDBC Database Connectivity

To accomplish this, first !ring up the Control )anel from the start menu and then clic, on the Administrative Tools icon. 'n the Administrative Tools dialog !o$, clic, on the Data Sources icon. 3. Connecting to a Database with JDBC Clic,ing on the Data Sources icon will !ring you to the ODBC Data Source Administrator /see 1igure +0 that will allow you to specify the name and the driver to !e used !y the application.

Figure 1 ODBC Data Source Administrator

-nce in the ODBC Data Source Administrator, clic, on the File DSN ta! and clic, on the Add !utton. The Microsoft ODBC Access Setup dialog !o$ appears ne$t as in 1igure 2.

Figure 2

There are two things that must !e completed in this dialog !o$&
By:Ritika Wason 2

JDBC Database Connectivity

+. Create a Data .ource (ame. 2. Clic, on the .elect !utton and literally find the purchase-rder.md! file that you previously created, as shown in 1igure 3.

Figure

t this point the D.( connection is complete and you can proceed to the second part of developing the code to utilize the data!ase and the D.( connection that you created. Deve!o"ing the Java#JDBC A""!ication 4ith the D.( defined, you now can !egin to develop the code to interact with the purchaseOrder data!ase. To accomplish this, ' have created two classes for the pro5ect. The first is the application called JDBCTest. ava, which contains the main method; and the second is called !unDB. ava, which neatly provides all of the functionality that you are interested in for this simple e$ample. 'n short, the !unDB class contains methods that encapsulate the !ehaviors that you want to demonstrate. The mission now is simple& #ou want to cover the following topics& +. 6oading the data!ase driver 2. Connecting to the D.( 3. Building a statement 7. 8$ecuting a %uery #ou can start !y developing the !unDB class. The structure of the class is very simple. #ou must import the ava.s"l.# pac,age to allow you access to the pac,age that contains the JDBC code. #ou also must provide two class attri!utes of type Connection and Statement. s the names imply, you will use these attri!utes to store the connection and statement information. ccess to these attri!utes is re%uired !y more than one method; thus, you need to define them for the scope of the class the framewor, for the !unDB class that is shown in 6isting +.
By:Ritika Wason 3

JDBC Database Connectivity

""9unDB import 5ava.s%l.:; pu!lic class 9unDB ; Connection connection; .tatement statement; ... behaviors < $isting 1 % $oa&ing the Database Driver The first piece of functionality that you need to address is loading the JDBC driver for the specific platform !y creating a method called loadDriver/ 0. 'n this case, you will load the -DBC"JDBC !ridge !y passing a string through the Class.forname/ 0 command as seen in 6isting 2. "" 6oad the Driver pu!lic void loadDriver/0 throws Class(ot1ound8$ception; Class.for(ame/=sun.5d!c.od!c.Jd!c-d!cDriver=0; < $isting 2 Note' ll of the methods in this class will thro$ the ClassNotFound%&ception e$ception. t this point in the development of the application, it is easier to catch all of the e$ceptions at the application level and not deal with them separately in each method.'f successful, this class will load the driver provided !y the Java implementation& sun. dbc.odbc.JdbcOdbcDriver. ( Connecting to the DSN -nce the driver is loaded, the ne$t order of !usiness is to ma,e the connection to the D.(, and thus the purchaseOrder data!ase that you created earlier. #ou create a method called ma'eConnection/ 0 and use the DriverMana(er class and its (etConnection/ 0 method, as seen in 6isting 3. "" Ma,e the Connection pu!lic void ma,eConnection/0 throws .*68$ception ; connection>DriverManager.getConnection/=5d!c&od!c&purchase-rder=0;
By:Ritika Wason 4

!isting

JDBC Database Connectivity

Note' The synta$ specifies the name of the D.(, and not the purchaseOrder.mdb file itself. n error will !e generated at this point if the D.( was not completed properly or if the data!ase is not in its proper place. 'f everything wor,s, you are now ready to do some actual .*6 code. ) B*i!&ing a State+ent & ,-ec*ting a .*ery 'n this case, you will issue an .*6 select statement that will select all of the records from the transaction ta!le. .868CT : 19-M Transaction #ou create a method called e&ecute)uer* / 0 and use the Statement class and its e&ecute / 0 method to initiate the .*6 select statement that you want. !oolean found9esults > statement. e$ecute /=.868CT : 19-M Transaction=0; 'f the statement e$ecution is successful, you retrieve the result set with the following code& 9esult.et set > statement.get9esult.et/0; 4ith the result set captured, you then can output the results via a method you supply, called displa*!esults / 0. 6isting 7 shows the entire e&ecute)uer* / 0 method. "" 8$ecute the %uery pu!lic void e$ecute*uery/0 throws .*68$ception ; !oolean found9esults > statement.e$ecute/=.868CT : 19-M Transaction=0; if/found9esults0; 9esult.et set > statement.get9esult.et/0; if/set?>null0 display9esults/set0; <else ; connection.close/0; < < $isting The displa*!esults/ 0 method is simply a loop that iterates through the 9esult.et. -ne of the interesting issues is how you can capture the metadata as well as the data itself. 9emem!er that metadata is actually data that descri!es data. The metadata contains such information as the num!er of columns and the column names. #ou use the !esultSetMetaData class to capture the metadata. Then, you can use methods such as the !esultSetMetaData class@s (etColumnCount/ 0 method.

By:Ritika Wason 5

JDBC Database Connectivity

/ Connecting to a Database with JDBC #ou create a single string that you will use to append all information that you want to output. That string can !e written to either the screen or a file. To ma,e things more interesting, you can create a document with AM6Bli,e tags using the column name as the tag names. #ou will use this techni%ue in future columns when you learn a!out AM6 parsing. n AM6 tag would loo, li,e this& C(ameDBase!allC"(ameD 6isting E shows the complete displa*!esults/ 0 method. "" Display the 9esults void display9esults/9esult.et rs0 throws .*68$ception ; 9esult.etMetaData metaData > rs.getMetaData/0; int columns>metaData.getColumnCount/0; .tring te$t>==; while/rs.ne$t/00; for/int i>+;iC>columns;FFi0 ; te$tF>=C=FmetaData.getColumn(ame/i0F=D=; te$tF>rs.get.tring/i0; te$tF>=C"=FmetaData.getColumn(ame/i0F=D=; te$tF>=n=; < te$tF>=n=; < .ystem.out.println/te$t0; < $isting % Considering the powerful functionality that you have covered, there really is not that much code involved. lthough hard coding the .*6 statement is o!viously not e$tensi!le, you can use this techni%ue to verify that you have successfully connected and interacted with the data!ase. The complete code for this application is presented in 6isting G. 4hen we run this application and successfully connect to the purchaseOrder data!ase, the output in 1igure 7 is produced. (ote that it is in pseudo AM6Bli,e tags. "" JDBCHTest I complete code pu!lic class JDBCTest ; pu!lic static void main/.tring argsJK0; 9unDB runDB > new 9unDB/0; try;
By:Ritika Wason 6

JDBC Database Connectivity

runDB.loadDriver/0; runDB.ma,eConnection/0; runDB.!uild.tatement/0; runDB.e$ecute*uery/0; <catch/8$ception e0; e.print.tac,Trace/0; < < < ""9unDB import 5ava.s%l.:; pu!lic class 9unDB ; Connection connection; .tatement statement; pu!lic void loadDriver/0 throws Class(ot1ound8$ception; Class.for(ame/=sun.5d!c.od!c.Jd!c-d!cDriver=0; < pu!lic void ma,eConnection/0 throws .*68$ception ; connection> DriverManager.getConnection/=5d!c&od!c&purchase-rder=0 < pu!lic void !uild.tatement/0 throws .*68$ception ; statement > connection.create.tatement/0; < pu!lic void e$ecute*uery/0 throws .*68$ception ; !oolean found9esults > statement.e$ecute/=.868CT : 19-M Transaction=0; if/found9esults0; 9esult.et set > statement.get9esult.et/0; if/set?>null0 display9esults/set0; <else ; connection.close/0; < < void display9esults/9esult.et rs0 throws .*68$ception ; 9esult.etMetaData metaData > rs.getMetaData/0;
By:Ritika Wason 7

JDBC Database Connectivity

int columns>metaData.getColumnCount/0; .tring te$t>==; while/rs.ne$t/00; for/int i>+;iC>columns;FFi0 ; te$tF>=C=FmetaData.getColumn(ame/i0F=D=; te$tF>rs.get.tring/i0; te$tF>=C"=FmetaData.getColumn(ame/i0F=D=; te$tF>=n=; < te$tF>=n=; < .ystem.out.println/te$t0; < < $isting (

Figure "

By:Ritika Wason 8

Vous aimerez peut-être aussi