Partial preview of the text
Download Programming With JDBC and more Assignments Java Programming in PDF only on Docsity!
Database Programming <= with JDBC = ee eee ee ee ee ee ee ee eee Va —e CONTENTS «+ — [1] Introduction of JDBC [2] JDBC Vs. ODBC [3] JDBC Architecture [4] JDBC API [5] JDBC Driver Types [6] Data Types in JDBC [7] Processing Queries [8] Database Exception Handling [9] Steps for Database Connectivity [10] JDBC API for Jaya Database Connectivity {11] DriverManager Class x [12] Statement Interface [13] PreparedStatement Interface [14] CallableStatement Interface (15] ResultSet Interface [16] Other APIs (MetaData) [17] DSN Less Connectivity [18] Steps to Create DSN for Access or Oracle Database [19] Summary [20] Self-Study Questions () Descriptive Questions (I) Multiple Choice Questions (M.C.Qs) JDBC stands for Java Database Connectivity. The java provides JOBC API to create Javi applications that are capable of interacting with a database. As we know that Java is an idea language for persistent data storage. By using class inheritance and data encapsulation, a Javé application developed to work with one type of data storage can be ported or extended tc work with another. An example for that is an application currently working with a RDBMS (Relational Database Management System) that is extended to use RMI to store data in a file. [20] C Scanned with OKEN Scanner Database Programming with JDBC n A general misunderstanding with Java is that database access can possible only with the JOBC API. Even though the JDBC provides lower level classes to manage database connections and transactions, it is not a compulsory component. We can easily connect our application with Microsoft SQL using MSSQLJAVA package instead of the MSSQLJDBC driver. [1] INTRODUCTION OF JDBC = eet { JDK 1.0 was released in\January 1996. It contained all the classes necessary to implement database access — although developers had to code their own connections, The JDK contained core classes such as java.net and java.io was grouped together to provide ‘the necessary classes to connect to a database and send-receive datd. Drawback of these classes for connection is that we have to create a socket and stream data to and form it to implement a simple transaction such like inserting or selecting data from database. So overcome from this drawback in February 1996, Sun released the JDBC as a separate package under the name java.sql. With the release of JDK 1.1, the JDBC package is not included as part of the core Java classes. The JDBC API is based on the SQL CLI (Call Level Interface). This standard explains how to access databases with function calls embedded in applications. Certain limitations are there when we are using JDBC. One of them is to connect to a database the JDBC-ODBC Bridge is used with native method calls and DLL (Dynamic Link Library) to connect to a database, so it don’t allowed its use in applet accessible through Internet. Because of potential security issues of an applet, the JDBC limits network connectivity to same host from which the applet was downloaded. Because of potential security risk of an applet, database must be installed on the same server as the HTTP server. PX f The following are characteristics of JDBC : : 1. It is call level SQL interface for Java. 2. It does not restrict the type queries passed to an underlying DBMS driver. 3. JDBC mechanisms are simple to understand and use. 4. It provides a Java Interface that stays consistent with the rest of the Java system. 5. JDBC may be implemented on top of common SQL level APIs. 6. It uses strong, static typing whenever possible. Some of the advantages of using of Java with JDBC are : 1. Supports a variety of relational Databases. 2. It is easy and economical. 3. It allows continuous usage of already installed databases. 4. It has a short development time. 5. Installation and version control is simple. ) C Scanned with OKEN Scanner Database Programming with JDBC 23 Ay JDBC ARCHITECTURE MC ‘The JDBC architecture describes the interaction of JDBC API with Java Application and Java applet. JDBC API consists of several call level interfaces for interaction with JDBC Driver Manager_and JDBC drivers for defining databases. JDBC API is responsible for transferring data between an application and a database. Figure 2.2 shows architecture of JDBC that represents the working of JDBC API, JDBC Driver and JDBC Driver Manager with multiple databases. Java Application F Java Applet (| Leet JDBC API 100) | ec yt JDBC Driver Manager | | | eo “<< . BC Driver\ {JDBC Driver Type-1 Type- 2 JDBC Drive: Type-4 er, ODBC Data Source Oracle SQL Server Figure 2.2 JDBC Architecture rhe i / The JDBC architecture divided into two parts JDBC Driver Types and JDBC APIs (java.sq! and javax.sql packages). Let us discuss in detail. } [4] JDBC API [- The JDBC API is_a collection of methods, classes and interfaces that enable Java_applications “to communicate with database. For this, database should be installed on the computer and the t C Scanned with OKEN Scanner 24 Advanced JAVA Programming (kp) RDBMS should provide a driver. JDBC classes and interfaces defined in the package Java.sq constitute the JDBC API. The Java program invokes the method of the JDBC API. The JDBC API then calls the IDBe driver and submits the queries to it. The JDBC driver then converts the queries to the SQ Statements that a database can understand. After the query has been performed, the JDBC drive, retrieves the result of the query form the database. The result is converted into the JDBC AP classes that are used by the Java Program. Then, the java program obtains the result of th query. The relations beeen java program, the JDBC API, the JDBC driver, and the database ; shown in figure 2.3. ) Java Program E & Wei, TES JDBC APE || S@l. JDBC Driver | lat ‘ A y (ag : Database Figure 2.3 Java Program and JDBC Using JDBC API a Java application can perform insert, update, delete and select rows in: database. It can also retrieve the data from the database and show it in a proper format t the user according to the SQL query, The JDBC API can be used in two-tier and three-tier database architectures. In two-tier architecture Java programs invoke methods of the JDBC API and communicate with the database serve! So, there is a direct interaction between Java programs and databases. In three-tier architectar a Java program eae queries to a server then server uses the JDBC API to interact wil the database server. C Scanned with OKEN Scanner HR Advanced JAVA Programming 4 2p, 26 Java Application JDBC API oe ' 4 Bridge Driver } : DSN t ODBC Driver io. Vata WA Database ee ee Figure 2.4 JDBC - ODBC Driver ( Advantage of the JDBC-ODBC Bridge is it allows access to almost any database, since { » database’s ODBC drivers are already available. Disadvantages are : 1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable. Performance is slowest in compare to all drivers because the JDBC calls are first convert to ODBC calls. ODBC calls are then converted to native database calls. The same ste are performed in reverse order when the result of the query is obtained. 2. 3. The client system requires the ODBC Installation to use the driver. 4. Not good for the Web Application or for large scale database based applications.) (2 Type 2 : Native-API /Partly-Java Driver : The JDBC Type 2 driver, or the native-API/partly-Java driver, communicates directly with! database server. Therefore, the vendor database library needs to be loaded on each client comp The Type 2 driver converts JDBC calls into_database-specific calls for databases. Example : Orac fe will have oracle Native API. ee _ C Scanned with OKEN Scanner Database Programming with JDBC 27 ( Java Application ) ( JDBC APT J a Native API Driver Native APT Database Figure 2.5 Native API/partly- Java Driver (asranage of Type2 driver are that they are typically offer better performance than the JDBC- DBC Bridge as the layers of communication (tiers) are less than and also it uses Native API which is Database specific. Disadvantages are ; 1. Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet. . Like Type 1 drivers, it’s not written in Java Language which forms a portability issue. . If we change the Database we have to change the Native API as it is specific to a database. 2. 3, 4. Mostly outdated now because it is not thread safe. 5. It is not suitable for distributed sid tap af Type 3 : Net-Protocol / All-Java Driver : Ronde. IAD ~The JDBC Type 3 driver, or the net-protocol/all-Java driver, follows a three-tiered approach. In the three-tiered approach, JDBC database requests are passed to a middle- tier server. The middle-tier server.then translates t the \e Tequests are passed to the database-specific native-connectivity interface and forwards the requests to the. database | server. If the middle-tier server is written in Java, it can use the Type 1 or Type 2 drivers to forward the requests to the database server. The three-tiered approach is illustrated in figure 2.6. =a C Scanned with OKEN Scanner Database Programming with JDBC 29 protocol. Therefore, client applications can communicate directly with the database server when Type4 JDBC drivers are used. The functionality of Type4 JDBC drivers is illustrated in figure 2.7. ) SS A ( Java Application | L JDBC API =| oat Thin’ Typed Driver Native ral Protocol Database Figure 2.7 Native Protocol/All Java Drivers The performance of Type 4 JDBC driver is better than other drivers because Type4 JDBC drivers do not have to translate database requests to ODBC calls or a native connectivity -interface or pass the request on to another server. A disadvantage of Type4 drivers, a different driver is needed for each database. Whereas advantages are : 1. The major benefit of using Type4 JDBC drivers is that they are completely written in Java to achieve platform independence. And using this benefit we can reduce deployment administration issues. So, it is most suitable for the web application. 2. Number of translation layers is very less ic. Type4 JDBC drivers don’t have to translate database requests to ODBC or a native connectivity interface or to pass the request on to another server. So, performance is typically quite good. 3. You need not to install special software on the client or server. Further, these drivers can be downloaded dynamically. [6] DATA TYPES IN JDBC The JDBC driver converts the Java data type to the appropriate JDBC type before sending it to the database. It uses a default mapping for most data types. For example, a Java int is converted to an SQLINTEGER. Default mappings were created to provide consistency between drivers. The following table summarizes the default JDBC data type that the Java data type is converted to when you call the setXXX (") method of the PreparedStatement or CallableStatement object or the ResultSet.getXXX ( ) method. | C Scanned with OKEN Scanner 30 Advanced JAVA Programming we i SQL JDBC / Java setXXX Bane VARCHAR java.lang.String setString Sak 2 CHAR java.lang.String setString | getSting LONGVARCHAR | java.lang.String Pacing | etString BIT boolean setBoolean | getBoolean —~ NUMERIC java.math.BigDecimal setBigDecimal | getBigDecimay —~ TINYINT bye setByte | getByte | —~ SMALLINT short setShort getShort INTEGER int setInt getInt BIGINT long setLong getLong REAL float ~ | setFloat getFloat FLOAT float setFloat getFloat | DOUBLE double setDouble getDouble BINARY byte[ ] setBytes getBytes DATE java.sql.Date setDate getDate TIME java.sql.Time setTime getTime TIMESTAMP java.sql. Timestamp setTimestamp getTimestamp CLOB java.sql.Clob setClob getClob BLOB java.sql.Blob setBlob getBlob ARRAY java.sql.Array setARRAY getARRAY REF java.sql.Ref SetRef getRef STRUCT java.sql.Struct SetStruct getStruct [7] PROCESSING QUERIES Following diagram shows java JDBE€ interaction of execution of a database query. Following six steps 1. Load driver. 2. Open and Return connection. 3. Create and Return statement. 4. Execute statement and Return statement if required, 5. Traverse Resultset. 6. Return records. the core JDBC components during tt are there: C Scanned with OKEN Scanner Advanced JAVA Programmin 32 ; iy (ay i f information SQLException provides following several kinds 0 oe s the Java Exception Message, avai 1. A string describing the error. This 1s used a: lay. the method getMessage(). ; KOFEN eae The “SQLState” string describing the error according to the QLState co cha a i NVeng i PEN SQL spe. « Yehtig The different values of this string are defined in the XO QL sp Cification ie ditleren : lly this will b 3. An integer error code that is specific to each vendor. Normally e the actual d e n | code returned by the underlying database. i dditional e; ; 4. A chain to a next Exception, which can be used to ia A tout ae: ‘formar, o This is frequently useful when you have (Ao PAE that yo User ty kn about, but you do not want to stop processing. Methods of java.sql.SQLException : iptio Return Type Method Description int getErrorCode() It is used to retrieve the vendor-specific exceptig code for this SQLException object. String getMessage() Gets the JDBC driver’s error Message for an er handled by the driver or gets the Oracle em number and message for a database error, SQLException getNextException() | It is used to retrive the €xception chained to thir SQLException object. String getSQLState() Retrieves the SQLState for this SQLExceptio object. void setNextException Adds a SQLException object to the end of th (SQLException ex) | chain. [9] STEPS FOR DATABASE CONNECTIVITY Mm - bis! K, Following are Steps to connect your application to Database, DEFINE THE CONNECTION URL : Class.forName(); © For jdbc-odbc bridge driver: Class. forName (sun jdbc.odbe.Jdbeo ¢ For oracle driver:- dbcDriver"), Class. forName Corale ibe driver OraceDriveey, © For Mysql driver:- : Class.forName("com.mysql.jdbé Driver", C Scanned with OKEN Scanner Database Programming with JDBC * ESTABLISHED THE CONNECTION : e For Oracle or other Sql server: Connection con =DriverManager.getConnection("url","user_name","pass"); e For Ms-Access Connection con =DriverManager.getConnection("url"," "," "); Or Connection con =DriverManager.getConnection("url"); % CREATE THE STATEMENT OBJECT : Statement stmt=con.createStatement( ); % EXECUTE A QUERY : stmt.executeQuery("sql"); or stmt.executeUpdate("sql"); * PROCESS THE RESULTS : ResultSet rs=stmt.execute Query("sql"); while(rs.next( )) { System.out.printIn(rs.getInt(id)); System.out.print(rs.getString(name)); } * CLOSE THE CONNECTION : a stmt.close(); con.close(); gd > ASI a Ob) Statement =y ResultSet : ame . Connection | os . ne FE is Se Ls v PreparedStatement : stor i Data Types: Date, ~ ht Time, Time-Stamp, 1. = Numeric, built in DriverManager Java types ,etc. a CallableStatement |) ea Figure 2.10 JDBC APIs - Figure 2.10 shows connectivity between all JDBC APIs which are discussed as follows. SU. BCA J2EE - 3 a C Scanned with OKEN Scanner Database Programming with JDBC a CallableStatement cst= con.prepareCall("{ call insertdata(?, ?) "; est.setString(1,sid); est.setString(2, sname); est.execute Upadate(); This method is having following signatures : + public CallableStatement prepareCall (String sq!) throws SQLException closeQ) : It is used to release the connection. They do not wait for release it automatically. It can be written like as follow : con.close(_ ); This method is having following signatures : e public void close( ) throws SQLException commit() : It is used to save the all state of the database which is changed _by transaction. It can be written like as Bila 3 con.commit( ); This method is having following signatures : e public void commit() throws SQLException ia 8 tis used to get the metadata (data about data) related to current connection with the database. ; provides the information related dataset like table driver name, driver type its version n_and So on. It is used DatabaseMetaData interface to get the informantion database drivers. For example : We Connection con; Con= DriverManager.getConnection(url," ", " "); DatabaseMetadata ds=con.getMetaData(); This-method is having following signatures : * public DatabaseMetaData getMetaData() throws SQLException setAutoCommit() : It is used to do auto commit with all the SQL statements. If we set the auto commit with the connection all the SOL statements executed and committed with together as individual transaction. It_has one parameter of Boolean type with it. [f we pass true_as_a parameter it enables es_the auto commit and if we pass false it disables the auto commit. Tap & Sample 3 C Scanned with OKEN Scanner JAVA Programming Advanced utoCommit(true)s con.setA' jonatures * 9 ig signal mots SQLException d is having followin Jean ac) © This metho mit(boo! e Public void setAutoCom 8. getAutoCommit() ¥ It is used_to get the cu For example : =con. getAutoCommit( ) rrent committed state. boolean b g following signatures : () throws SQLException This method is havin; ¢ Public void boolean getAutoCommit! 9, rollback() : It_used to cancel effect of current running transaction. con.rollback(); This method is having following signatures - © public void commit() throws SQLException 10. isClosed() : It is used to check whether the connection has been closed or not. a eal For example : boolean b=con.isClosed(); This method is having following signatures : * public boolean isClosed() throws SQLException. [11] DRIVERMANAGER CLASS The DriverManager cla: _belongs to java.sql package. It c msists of the static 9 iq! Pp ig Onsi: nanage the JDBC Driver S. Each and E) wery JDBC Driver must Tegister wi he me verMan class. There are man: i vi y JDBC drivers used i i Serve Driver for Microsoft Access is different ae Srudbien e sy ie class controls the interface between the Bakek. ee for Oracle. In short, DriverMan! —~—Hppilcation_and_ JDBC Drivers. DriverManagel! important method is getConnection ( ~=8et\onnection () method which is used to establish the connectiot ' the different datab. ase follows : servers. It has three overloaded signatures (p hich ate ures (parameters) whi¢ SQLExceptii nm getConnection(Str; Xceptiion n(String url, String username, String pass word) ti? C Scanned with OKEN Scanner Ee Advanced JAVA Programming 38 [12] STATEMENT INTERFACE This interface object is used_to een flowing after executing the statement. It is mil pret poli, , +] different types SQL Statements. &% azn] bi Dud Ur } i h é 2 using select qu i -« used to fetch the records from the database OY ene ce an ae Ae RealtSe object at a time. It passes a P' si ty NURSES the records from the database. , SQL Statements and obtain the resy he St = different, types of methods eats ai ‘ ye i) aly \y 1. executeQuery() : tern For example : Statement st=con.createStatement(); Aen Sess " la , Resultset rs= st.excuteQuery("select * from ta ak This method is having following signatures : i eption * public ResultSet executeQuery(String sql) throws SQLExcep' 2. executeUpdate() : This methods is used to perform the insert, update_and delete operations on_the = Tecords the database. Iftetums the integer value which indicates no. of records updated in the databy It passed a SQL statement as a parameter which updates the records of the database, For example : r —= Statement st=con.createStatement(); This method is having following signatures : © public int executeUpdate(String sql) throws SQLException F 3. execute(): Con pertorn gpa Bho owls , dep , olen. Itis used to execute the SQL statements which Teturn the mult Mis use - iple results. It returns the Book indicating value if it returns the true then it defines that the next result is ResultSet obj and if it returns the fal se then it defines no. of Tecords updated or no more result is th It passes any SQL statement as parameter, in ae mi For example : cling wa2gthor may WES Arutrorbull or Hol a "create table tablename(fieldname type(size), fieldname Statement st=con.createStatement(); String sql = | type(size))"; St.execute(sql); This method. is having following Signatures : * public boolean execute(String sql) throws SQLException = | C Scanned with OKEN Scanner | base Programming with JDBC Data | Example of Statement Interface : ling java.sql.*; I class JdbcDemo { public static void main(String a[]) { Connection conn; Statement stmt; ResultSet rs; try { Class.forName("sun.jdbc.odbe.JdbcOdbeDri String url = “jdbc:odbe:emp"; conn = DriverManager.getConnection(url); stmt = conn.createStatement(); Ts while(rs.next()) { System.out.println("Employee No. : System.out.println("Employee Salary: } rs.close(); stmt.close(); conn.close(); } catch(SQLException ex) stmt.executeQuery("Select * from Emp"); System.out.printIn("Employee Name : { System.out.printIn("ERROR in Connection : } catch(ClassNotFoundException ex) { System.out.printIn("ERROR Class Not Found :" + ex.getMessage()); 0 ver"); "+ rs.getint(1)); :" + rs.getString(2)); " + rs.getFloat(3)); + ex.getMessage()); C Scanned with OKEN Scanner