Jdbc 1
Upcoming SlideShare
Loading in...5
×
 

Jdbc 1

on

  • 345 views

JDBC

JDBC

Statistics

Views

Total Views
345
Views on SlideShare
345
Embed Views
0

Actions

Likes
0
Downloads
10
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Jdbc 1 Jdbc 1 Document Transcript

  • JDBC - 1 JDBC What is JDBC? 1. JDBC – Java Database Connectivity package lets programmers connect to a database, query it, or update it, using the Structured Query Language or SQL. 2. JDBC is Java application programming interface (API) that allows Java programmers to access database management system from a Java program. 3. JDBC consists of a set of classes and interfaces written in Java. 4. It allows the programmer to send SQL statements to a database server for execution and retrieve results of the queries. 5. It provides for portability across different database servers and hardware architectures. 6. JDBC is an alternative to ODBC. ODBC technology was developed by Microsoft ant it is called Open DataBase Connectivity. Whereas ODBC provides a C language interface, JDBC provides Java language interface. 7. Thus, the primary purpose of JDBC (and also ODBC) is to provide a means for the developer to issue SQL commands and process the results in a database-independent manner. 8. The classes that we use for JDBC are contained in the java.sql and javax.sql packages. What are the JDBC Components? JDBC includes 4 components: 1. The JDBC API a. The JDBC API provides the facility for accessing a relational database from Java programs. b. JDBC can also access multiple data sources in a distributed and heterogeneous environment. c. This API technology provides a industry standard for connecting Java programs and a wide range of databases. d. The user can execute the SQL statements, retrieve results, and update the data and also access it anywhere within a network because of it's "Write Once, Run Anywhere" (WORA) capabilities. e. Due to JDBC API technology, user can also access other tabular data sources like spreadsheets or flat files. JDBC API is a part of the Java platform ((Java SE and Java EE) f. JDBC API is divided into two packages (a) java.sql and (b) javax.sql 2. JDBC Driver Manager a. The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. b. The Driver manager is the backbone of the JDBC architecture. c. The main responsibility of JDBC database driver is to load all the drivers found in the system properly and to select the most appropriate driver for opening a connection to a database. Prof. Mukesh N. Tekwani Page 1 of 24
  • JDBC d. The Driver Manager also helps to select the most appropriate driver from the previously loaded drivers when a new open database is connected. e. Tasks performed by the DriverManager are: i. Locate a driver for a particular database ii. Process JDBC Initialization calla iii. Provides entry points to JDBC function calls for each specified driver iv. Perform parameter and sequence validation for JDBC calls. f. The DriverManager class works as the interface between the application (UI) and the ODBC driver created to communicate with the Microsoft Access database. g. Some of the methods of DriverManager class are: i. getConnection(JDBC:ODBC:Name of DSN, <username>, <password>) 3. The JDBC Test Suite. a. The function of JDBC driver test suite is to ensure that the JDBC drivers will run user's program. b. The test suite of JDBC API is very useful for testing a driver based on JDBC technology during testing period. 4. JDBC-ODBC Bridge a. The Java-ODBC bridge provides JDBC access via ODBC drivers. We must load ODBC binary code onto each client machine that uses this driver. b. The JDBC-ODBC bridge is also known as JDBC Type 1 driver is a database driver that utilize the ODBC driver to connect to the database. c. The ODBC driver translates JDBC method calls into ODBC function calls. The Bridge implements JDBC for any database for which an ODBC driver is available. Java Application JDBC API JDBC Driver Manager JDBC Driver API JDBC-ODBC Bridge Vendor Specific ODBC Driver Vendor Specific JDBC Driver Database Database Page 2 of 24 mukeshtekwani@hotmail.com
  • JDBC - 1 Explain the JDBC Two-Tier and Three-Tier Processing Models The JDBC API supports both two-tier and three-tier processing models for database access. The Two-Tier Architecture for Data access: 1. In the two-tier model, a Java applet or application talks directly to the data source. 2. This requires that a JDBC driver that can communicate with the particular data source being accessed. 3. A user's commands are delivered to the database or other data Java Application source, and the results of those statements are sent back to the user. 4. The data source may be located on another machine to which the JDBC user is connected via a network. This is referred to as a client/server configuration; the user's machine is called the client, and the machine that has the data source is the server. DBMS The Three-Tier Architecture for Data access: 1. In the three-tier model, data base access commands are sent to a "middle tier" of services, which then sends the commands to the data source. 2. The data source processes the commands and sends the results back Java Applet to the middle tier, which then sends them to the user. 3. Advantages of three-tier: a. The three-tier model is useful because the middle tier makes it possible to maintain control over access and the kinds of Application Server updates that can be made to corporate data. (Java) b. Another advantage is that it simplifies the deployment of JDBC applications. 4. The Java applet communicates with the server machine through HTTP, RMI or CORBA. 5. A DBMS proprietory protocol is used to communicate with the DBMS. DBMS 6. The middle-tier is written in C, C++ or Java. What are the JDBC Drivers? A JDBC driver is needed to connect to a database and access its data. The driver types help in categorising the technology used to connect to a database. These drivers can be divided into 4 broad categories as follows: 1. Type 1 or JDBC-ODBC Bridge 1. The JDBC type 1 driver, also known as the JDBC-ODBC bridge is a database driver that uses the ODBC driver to connect to a database. 2. The driver converts or translates JDBC method calls into ODBC function calls. The bridge is usually used when there is no pure-Java driver available for a particular database. 3. The driver is platform-dependent as it makes use of ODBC which in turn depends on native libraries of the operating system. 4. If this driver is used, than ODBC must be also installed on the computer; this is called a dependency. Prof. Mukesh N. Tekwani Page 3 of 24
  • JDBC 5. The JDBC-ODBC bridge consists of an ODBC driver which uses the services of JDBC driver to connect to a database. 6. The advantage of this is : almost any database for which ODBC driver is installed can be accessed. 7. The disadvantages of this are: a. There is a performance overhead since the calls have to go through the JDBC bridge to the ODBC driver, then to the native database connectivity interface. b. The ODBC driver must be installed on the client machine. 2. Type 2 or Native API Driver 1. 2. 3. 4. This is a native API driver and it uses the client-side libraries of the database.. Its function is to convert JDBC calls into calls on the client API for that database Client -> JDBC Driver -> Vendor Client DB Library -> Database The type 2 driver is not written entirely in Java as it interfaces with non-Java code that makes the final database calls. 5. The driver is compiled for use with the particular operating system. 6. Like the bridge driver, this style of driver requires that some binary code be loaded on each client machine. 7. The type 2 driver provides more functionality and performance than the type 1 driver as it does not have the overhead of the additional ODBC function calls. 8. Type 2 drivers use a native API to communicate with a database system. Java native methods are used to invoke the API functions that perform database operations. Type 2 drivers are generally faster than Type 1 drivers. 9. A Type 2 JDBC driver may require some Database Management System (DBMS) networking software to be installed. 10. The disadvantages of this driver are: (a) the vendor client library must be installed on the client machine, (b) It cannot be used in internet due the client side software needed, and (c) All databases do not give the client side library. 3. Type 3 or Network Protocol Driver 1. The JDBC type 3 driver, also known as the network-protocol driver is a database driver implementation which makes use of a middle-tier between the calling program and the database. 2. Client -> JDBC Driver -> Middleware-Net Server -> Any Database 3. The middle-tier (application server) converts JDBC calls directly or indirectly into the vendor-specific database protocol. 4. The protocol conversion logic resides not at the client, but in the middle-tier. 5. The same driver can be used for multiple databases. It depends on the number of databases the middleware has been configured to support. 6. The type 3 driver is platform-independent as the platform-related differences are taken care by the middleware. 7. Also, making use of the middleware provides additional advantages of security and firewall access. 8. These drivers use a networking protocol and middleware to communicate with a server. The server then translates the protocol to DBMS function calls specific to DBMS. Page 4 of 24 mukeshtekwani@hotmail.com
  • JDBC - 1 9. Type 3 JDBC drivers are the most flexible JDBC solution because they do not require any native binary code on the client. 10. The type 3 driver is written entirely in Java. 11. In general, this is the most flexible JDBC API alternative. Advantages 1. Since the communication between client and the middleware server is database independent, there is no need for the vendor database library on the client machine. 2. The client to middleware need'nt be changed for a new database. 3. The Middleware Server can provide typical middleware services like caching (connections, query results, and so on), load balancing, logging, auditing etc.. 4. It can be used in internet since there is no client side software needed. 5. At client side a single driver can handle any database. Disadvantages 1. Requires database-specific coding to be done in the middle tier. 2. An extra layer added may result in a time-bottleneck. 4. Type 4 or Native Protocol Driver 1. The JDBC type 4 driver, also known as the native-protocol driver is a database driver implementation that converts JDBC calls directly into the vendor-specific database protocol. 2. Client Machine -> Native protocol JDBC Driver -> Database server 3. This is the highest performance driver available for a database. 4. The type 4 driver is written completely in Java and is therefore platform independent. It is installed inside the Java Virtual Machine (JVM) of the client. 5. It provides better performance compared to the type 1 and 2 drivers as it does not have the overhead of conversion of calls into ODBC or database API calls. 6. It also does not need associated software to work. 7. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. 8. Type 4 drivers are all Java drivers. This means that there is no client installation or configuration. Advantages These drivers don't translate the requests into db request to ODBC or pass it to client api for the db, nor do they need a middleware layer for request indirection. Thus the performance is considerably improved. Disadvantage At client side, a separate driver is needed for each database. Prof. Mukesh N. Tekwani Page 5 of 24
  • JDBC CREATING A DATABASE THROUGH JDBC: Creating a database through JDBC involves the following steps: 1. Import the required package : import java.sql.*; 2. Register the JDBC driver – The Class.forName() method is used to load the database driver. “Class” is a built-in class. forName() is a method and it has format as follows: a. Class.forName(String classname) – this will return the Class object associated with the class with the given string name. We pass the argument “sun.jdbc.odbc.JdbcOdbcDriver”. The compiler will search for this class at run time. 3. Open a connection – The method DriverManager.getConnection() is used to create a Connection object. This object will represent a physical connection with the database server. The DriverManagaer will use the first driver it can find to successfully connect to the given database. The constructors of this are: a. Connection getConnection(string url); b. Connection(String url, String user, String password); 4. Executing a Query – For submitting and building an SQL statement, we need an object of type Statement. The interface Statement supports the following methods: a. ResultSet executeQuery(String sql); - it executes the given SQL statement which returns an object of type ResultSet. This statement must be used to execute a SELECT statement. b. int executeUpdate(String sql) – it executes the given statement which may be INSERT, UPDATE or DELETE statement. This method returns a count of the number of statements that were affected by the SQL statement, or 0 for statements that do not return a count. This method can also execute DDL statements such as CREATE TABLE and DROP TABLE. THE JAVA.SQL PACKAGE: The java.sql package contains many classes and interfaces that are used by the JDBC API. These classes and interfaces enable the following basic database functions: creating, opening and managing connections to a database, executing SQL statements, processing the results in the ResultSet, and closing the connection. Some of the Classes and Interfaces of java.sql package are explained below: 1. The DriverManager This class works as an interface between the application (UI) and the Microsoft Access database. It provides the methods for managing database drivers. getConnection(jdbc:odbc:name of DSN, <username>, <password>) This method attempts to establish a connection to the specified database by invoking the JDBC:ODBC bridge and by accepting the name of the DNS as an argument. The system DSN knows where the Access database is. Once a physical connection with a database has been established, we initialize the SQL queries that will be used on the database. Page 6 of 24 mukeshtekwani@hotmail.com
  • JDBC - 1 ResultSet: The data records retrieved from the database table are held in ResultSet object. Once the table is held in the ResultSet object, the records and the individual fields of each record can be manipulated. The ResultSet contains zero, one or many records. Since this object is created in memory, its contents cannot be seen. To see the data held within the ResultSet object, its each row must be read. We can read each record by using a while loop. The rs.next() method is used in a loop to get one row at a time from the table. 2. Connection Interface: A Connection object represents a connection with a database. SQL statements can be executed and ResultSets are returned from the table. Methods used from Connection interface: a) void close(); The close() method will release the database resources and JDBC resources. b) Statement createStatement(); This method returns a new object that can be used to execute SQL statements. c) void close() - immediately closes the current connection and the JDBC resources it created. 3. Statement Interface: A Statement object executes statements and obtains results after their execution. The results are in the form of ResultSet object. Methods used from Statement interface: a) ResultSet executeQuery(String sqlstmt) - This method executes a SQL query that returns a single ResultSet object. b) int executeUpdate(String sqlstmt) - This method executes the SQL UPDATE, DELETE or INSERT statements. It also executes the DDl statements such as CREATE TABLE. It returns a row count or -1 for a statement without an update count. c) int getUpdateCount – It returns the number of rows affected by the previous update statement or -1 if the preceding statement did not have an update count. d) boolean isClosed() – returns true if this statement is closed. 4. PreparedStatement Interface: This interface extends the Statement interface. If a particular SQL statement has to be executed many times, it is precompiled and stored in a PreparedStatement object. This object is then used many times to execute the statement. Prof. Mukesh N. Tekwani Page 7 of 24
  • JDBC Methods used from PreparedStatement interface: a) executeQuery() - This method executes prepared SQL query and returns a ResultSet object.. b) executeUpdate() - This method executes the prepared SQL UPDATE, DELETE or INSERT statements. It returns the number of rows affected. For DDL statements such as CREATE TABLE, it returns a 0. c) void setXxx(int n, Xxx x)– sets the value of the nth parameter to x. Xxx is data type. d) void clearParameters() – clears all current parameters in the prepared statement. Example: Consider a query for all books by a publisher, independent of the author. The SQL query is: SELECT Books.Price, Books.Title FROM Books, Publishers WHERE Books.Publisher_Id = Publishers.Publisher_Id AND Publishers.Name = the name from the list box Instead of building a separate query each time the user gives this query, we can prepare a query with a host variable and use it many times, each time filling in a different string for the variable. We can prepare this query as follows: String publisherQuery = “SELECT Books.Price, Books.Title” + “ FROM Books, Publishers” + “ WHERE Books.Publisher_Id = Publishers.Publisher_Id AND Publishers.Name = ?”; PreparedStatement publisherQueryStat = conn.prepareStatement(publisherQuery); Before executing the prepared statement, we must bind the host variables to actual values with a set method. There are different set methods for different data types. To set a string to a publisher name: publisherQueryStat.setString(1, publisher) The first argument is the position number of the host variable that we want to set. The position 1 denotes the first ?. The second argument is the value we want to assign to the host variable. Once the variables have been bound to values, we can execute the query: ResultSet rs = publisherQueryStat.executeQuery() 5. ResultSet Interface: The data generated by the execution of a SQL statement is stored in a ResultSet object.This object can access only one row at a time. This row is called as its current row. When the SQL statement is re-executed, the current recordset is closed and a new RecordSet object is created. Methods used from ResultSet interface: a) void close()- This method is used to release a ResutSet. Page 8 of 24 mukeshtekwani@hotmail.com
  • JDBC - 1 b) void getString()- This method is used to get the value of a column in the current row. c) next() – A ResultSet is initially positioned before its first row. The first time we call the next() method, it makes the first row as the current row. The second time we call the next() method, the second row becomes the current row, etc d) getXxx(int col no) and getXxx(String collabel) - it returns the value of a column with the given column number or label, converted to the specified type. Here Xxx is a data type such as int, double, String, Date, etc. e) int findColumn(String colname) – gives the column index associated with a column name. f) boolean isClosed() – returns true if this statement is closed. g) boolean first() and boolean last() – moves the cursor to the first or last row. Returns true if the cursor is positioned on a row. h) boolean isFirst() and boolean isLast()– Returns true if the cursor is positioned on first row or last row. 6. ResultSetMetaData Interface: This object is returned by the getMetaData() constructor. It gives information about number of columns, their types and properties or in general about the structure of a database. Methods used from ResultSet interface: a) getColumnCount()- This method returns the number of columns in the ResutSet. b) String getColumnName(int) – This method returns the name of a specific column. c) getTableName() – This method returns the name of a table. d) DataBaseMetaData metadt = conn.getMetaData(); DATA SOURCE NAME (DSN) If the original database is created in, say Microsoft Access, then we create a DSN. DSN stands for Data Source Name. A DSN is itself a data structure that contains information about the database, such as, the driver type, the database name, the actual location of the database on the hard disk (i.e., the path), the user name and a password. All this information in DSN is required by ODBC to drivers for creating a connection to the database. DSN is used from an application to send or receive data to the database. DSN is stored in the system registry. CREATING A TABLE Program 1: Creating a Access table “TYBSC” in “college” database import java.sql.*; public class CreateTYBSc { public static void main(String args[ ]) { Prof. Mukesh N. Tekwani Page 9 of 24
  • JDBC // declaring the connection object named conn Connection conn; // declaring the string object called createString String createString; //Load the createString with createString = "create table "(RollNo Number, " "NAME Text(25), " "Marks1 Number, " "Marks2 Number, " "Marks3 Number)"; the 'Create Table' stmt TYBSc " + + + + + //declaring the statement object called stmt Statement stmt; try { // Loading the Java JDBC:ODBC driver Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); } // Handling the class not found exception if thrown catch(ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } // try block-create a connection to Access database try { // Creating a Connection called conn conn = DriverManager.getConnection("jdbc:odbc:college"); // creating a statement object called stmt stmt = conn.createStatement( ); //Passing the executeUpdate() method the 'Create Table' stmt.executeUpdate(createString); // Indicate that the table was successfully created System.out.println("The TYBSc table has been created succssfully"); // Closing the statement object stmt stmt.close( ); // Closing the connection object conn conn.close( ); } //end of try block Page 10 of 24 mukeshtekwani@hotmail.com
  • JDBC - 1 // catch block to deal with any SQL exception thrown catch(SQLException ex) { System.err.println("SQLException:"+ex.getMessage( )); } } } // End of main() method // End of class TYBSc Analysis of the program: 1. Choose appropriate driver Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); This loads the jdbc-odbc bridge driver. 2. Creating a connection using the DriverManager class: DriverManager.getConnection(“jdbc:odbc:college”); This calls the DriverManager class to create the Connection object. For connecting to the JDBC data source the name is required to be given in the URL format as follows: jdbc:<subprotocol> : <dsn>. Here dsn is the data source name. INSERT RECORDS IN A TABLE Program 2: Program to insert records (rows) into a table // Inserting rows in to the Access table 'TYBSc' using Java code import java.sql.*; public class InsertStudent { public static void main(String args[ ]) { Connection conn; Statement stmt; String query = "select RollNo, Name, Marks1, Marks2, Marks3 from TYBSc"; try { Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException e) { System.err.print("ClassNotFoundException : System.err.println(e.getMessage( )); } "); try Prof. Mukesh N. Tekwani Page 11 of 24
  • JDBC { Conn = DriverManager.getConnection("jdbc:odbc:college"); stmt = conn.createStatement( ); // Inserting five records into the table 'TYBSc', // using the INSERT statement stmt.executeUpdate("insert into TYBSc " + "values('1', 'Anita', 80, 90, 85)"); stmt.executeUpdate("insert into TYBSc " + "values('2', 'Mumtaz', 65, 67, 76)"); stmt.executeUpdate("insert into TYBSc " + "values('3', 'Raj', 66, 77, 87)"); stmt.executeUpdate("insert into TYBSc " + "values('4', 'Geeta', 77, 77, 82)"); //Print message at prompt indicating rows inserted System.out.println("Records Insertednn"); // Query database to view the data inserted // use the RecordSet object rs ResultSet rs = stmt.executeQuery(query); //Print a 'Row Header' at the system prompt System.out.print("Roll Not"); System.out.print("Namett"); System.out.print("Marks1tt"); System.out.print("Marks2tt"); System.out.print("Marks3tt"); System.out.println("Total"); //Retrieve records from RecordSet rs and //displaying them at the system prompt //We use a column name to extract a column value //from the RecordSet while (rs.next()) { int r = rs.getInt("Rollno"); String n = rs.getString("Name"); int m1 = rs.getInt("Marks1"); int m2 = rs.getInt("Marks2"); int m3 = rs.getInt("Marks3"); int total = m1 + m2 + m3; //not stored in dbase System.out.print(r + "t"); System.out.print(n + "tt"); System.out.print(m1 + "tt"); System.out.print(m2 + "tt"); System.out.print(m3 + "tt"); System.out.println(total); } Page 12 of 24 mukeshtekwani@hotmail.com
  • JDBC - 1 } } // Closing the Statement object stmt stmt.close( ); // Closing the connection object conn conn.close( ); // End of try block //Exception handling done here catch(SQLException ex) { System.err.println("SQLException:"+ex.getMessage( )); } } // End of main() method // End of class InsertStudent GETTING DATA FROM COLUMNS OF A TABLE (ACCESSORS): 1. There are various accessors that permit us to read the contents of a field. 2. Each accessor has two forms, one takes a numeric argument and the other takes a string argument. 3. When we give supply a numeric argument we are referring to the column with that number. E.g., rs.getInt(1)returns the value of the first column. 4. When we supply a string argument we refer to the column in the result set with that name.E.g., rs.getInt("Rollno") returns the value of the column with the name RollNo. 5. The following are the getXXX() methods available to get the column data from the current row: String boolean int float byte double long getString(String columnname); getBoolean (String columnname); getint(String columnname); getfloat(String columnname); getByte(String columnname); getDouble(String columnname); getLong(String columnname); UPDATE RECORDS IN A TABLE Program 3: Update the TYBSc table by assigning a mark of 80 in field Marks1 if Marks1 lies between 75 and 79 (both inclusive). import java.sql.*; public class UpdateStudent { public static void main(String args[ ] ) { Connection conn; Prof. Mukesh N. Tekwani Page 13 of 24
  • JDBC Statement stmt; String query = "select RollNo, Name, Marks1, Marks2, Marks3 from TYBSc"; try { Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException clsnotfndExcep) { System.out.print("ClassNotFoundException : "); System.out.println(clsnotfndExcep.getMessage( )); } try { Conn = DriverManager.getConnection("jdbc:odbc:college"); stmt = conn.createStatement( ); //Update 5 records in table ‘TYBSc’ using UPDATE statement stmt.executeUpdate("update TYBSc " + "set Marks1 = 80 where Marks1 <=79 and Marks1 >= 75"); //Print message indicating rows inserted System.out.println("Record Updatednn"); //Query the database to view the data ResultSet rs = stmt.executeQuery(query); //Print ‘Row Header’ at the system prompt System.out.print("Roll Not"); System.out.print("Namett"); System.out.print("Marks1tt"); System.out.print("Marks2tt"); System.out.print("Marks3tt"); System.out.println("Total"); //Retrieve records from RecordSet rs & displaying them //at the system prompt while (rs.next( ) ) { int r = rs.getInt("Rollno"); String n = rs.getString("Name"); int m1 = rs.getInt("Marks1"); int m2 = rs.getInt("Marks2"); int m3 = rs.getInt("Marks3"); int total = m1 + m2 + m3; //not stored in dbase System.out.print(r + "t"); System.out.print(n + "tt"); System.out.print(m1 + "tt"); Page 14 of 24 mukeshtekwani@hotmail.com
  • JDBC - 1 System.out.print(m2 + "tt"); System.out.print(m3 + "tt"); System.out.println(total); } // closing the Statement object stmt stmt.close( ); // closing the connection object conn conn.close( ); } // End of try block } //Exception handling done here catch(SQLException sqlExcep) { System.err.println("SQLException: " + sqlExcep.getMessage( )); } } // End of main() method // End of class UpdateProduct DELETE RECORDS FROM A TABLE Program 4: Delete records from the TYBSc table if Marks1 < 75 import java.sql.*; public class DeleteStudent { public static void main(String args[ ] ) { Connection conn; Statement stmt; String query = "select RollNo, Name, Marks1, Marks2, Marks3 from TYBSc"; try { Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException clsnotfndExcep) { System.out.print("ClassNotFoundException : "); System.out.println(clsnotfndExcep.getMessage( )); } try { conn = DriverManager.getConnection("jdbc:odbc:college"); stmt = conn.createStatement(); //Delete a record from the table Prof. Mukesh N. Tekwani Page 15 of 24
  • JDBC stmt.executeUpdate("Delete from TYBSc " + " where Marks1 < 75"); // Printing a message at the system prompt indicating rows // inserted System.out.println("Record Updatednn"); // Querying the Access database to view the data // inserted using the RecordSet object rs ResultSet rs = stmt.executeQuery(query); // Printing a static ‘Row Header’ at the system prompt System.out.print("Roll Not"); System.out.print("Namett"); System.out.print("Marks1tt"); System.out.print("Marks2tt"); System.out.print("Marks3tt"); System.out.println("Total"); // Retrieving records from the RecordSet rs and // displaying them at the system prompt while (rs.next()) { int r = rs.getInt("Rollno"); String n = rs.getString("Name"); int m1 = rs.getInt("Marks1"); int m2 = rs.getInt("Marks2"); int m3 = rs.getInt("Marks3"); int total = m1 + m2 + m3; //not stored in dbase System.out.print(r + "t"); System.out.print(n + "tt"); System.out.print(m1 + "tt"); System.out.print(m2 + "tt"); System.out.print(m3 + "tt"); System.out.println(total); } // closing the Statement object stmt stmt.close( ); // closing the connection object conn conn.close( ); } // End of try block // Exception handling done here catch(SQLException sqlExcep) { System.err.println("SQLException: " + Page 16 of 24 mukeshtekwani@hotmail.com
  • JDBC - 1 sqlExcep.getMessage( )); } } } // End of main() method // End of class DeleteStudent DROP A TABLE Program : This program drops the Access table TYBSc //Drop the Access table 'TYBSc’ import java.sql.*; public class DropTYBSc { public static void main(String args[ ] ) { Connection conn; Statement stmt; try { Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException e) { System.err.print("ClassNotFoundException : System.err.println(e.getMessage( )); } try { "); conn = DriverManager.getConnection("jdbc:odbc:college"); stmt = conn.createStatement( ); //Delete table 'TYBSc', using the executeUpdate( ) method stmt.executeUpdate("Drop table TYBSc " ); //Print a message indicating rows inserted System.out.println("Table TYBSc Deletedn"); // Closing the Statement object stmt stmt.close( ); // Closing the connection object conn conn.close( ); } // End of try block // Exception handling done here catch(SQLException ex) { Prof. Mukesh N. Tekwani Page 17 of 24
  • JDBC System.err.println("SQLException: " + ex.getMessage( )); } } } // End of main() method // End of class DropTYBSc ALTER A TABLE Program : This program alters the Access table TYBSc by adding a column called ‘Result’ of type Text (25 cols) // Alter the Access table 'TYBSc' import java.sql.*; public class AlterTYBSc { public static void main(String args[ ] ) { Connection conn; Statement stmt; try { Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException e) { System.out.print("ClassNotFoundException : "); System.out.println(e); } try { conn = DriverManager.getConnection("jdbc:odbc:college"); stmt = conn.createStatement( ); // Alter the table 'ProductMaster', using the stmt.executeUpdate("ALTER TABLE TYBSC ADD RESULT TEXT(20)"); //Print a message indicating table is altered System.out.println("Table TYBSc Alteredn"); // Closing the Statement object stmt stmt.close( ); // Closing the connection object conn conn.close( ); } // End of try block // Exception handling done here catch(SQLException ex) { Page 18 of 24 mukeshtekwani@hotmail.com
  • JDBC - 1 System.err.println("SQLException: " + ex.getMessage( )); } } } // End of main() method // End of class DropProduct ACCESSING COLUMNS BY COLUMN INDEXES Program : This program demonstrates how we can use the column indexes to identify the columns of the current row. stmt = conn.createStatement( ); ResultSet rs = stmt.executeQuery(“SELECT RollNo, Name, Marks1 FROM TYBSc”); while (rs.next()) { int r = rs.getInt(1); String n = rs.getString(2); int m1 = rs.getInt(3); System.out.print(r + "t"); System.out.print(n + "tt"); System.out.print(m1 + "tt"); } PREPARE STATEMENT Program : This program creates a table called SYBSc and then uses the PrepareStatement to insert 5 records into the table. // This program illustrates the concept of Prepare statement; // First we create a table called SYBSc and then insert 5 records // in this table import java.sql.*; public class PreparedStudent { public static void main(String args[]) { Connection conn; Statement stmt; PreparedStatement ps; ResultSet rs; String url = "jdbc:odbc:college"; //we have created a DSN named ‘college’ for database String createString = "create table SYBSc " + Prof. Mukesh N. Tekwani Page 19 of 24
  • JDBC "(RollNo Number, " + "NAME Text(25), " + "Marks1 Number, " + "Marks2 Number, " + "Marks3 Number, " + "Total Number)"; //following is the data we will enter into the table int rno[] = {21, 22, 23, 24, 25}; String stname[] = {"Namita","Aakash","Bina","Payal","Geet"}; int mksC[] = {89, 87, 90, 92, 91}; int mksOS[] = {54, 65, 76, 87, 98, 99}; int mksCPP[] = {44, 55, 66, 77, 88}; try { Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException e) { System.err.print("ClassNotFoundException: " + e); } try { conn = DriverManager.getConnection(url); stmt = conn.createStatement(); stmt.executeUpdate(createString); System.out.println("The SYBSc table has been created successfully"); // Inserting five records into the table 'SYBSc', // using the INSERT statement ps = conn.prepareStatement("INSERT INTO SYBSC (RollNo, Name, Marks1, Marks2, Marks3) values(?, ?, ?, ?, ?)"); for(int i = 0; i < 5; i++) { ps.setInt(1, rno[i]); ps.setString(2, stname[i]); ps.setInt(3, mksC[i]); ps.setInt(4, mksCPP[i]); ps.setInt(5, mksCPP[i]); ps.executeUpdate(); //important step } stmt.executeUpdate("UPDATE SYBSC SET TOTAL = MARKS1 + MARKS2+ MARKS3"); // Query the Access database to view data inserted Page 20 of 24 mukeshtekwani@hotmail.com
  • JDBC - 1 // using the RecordSet object rs rs = stmt.executeQuery("SELECT * FROM SYBSC"); // Print a 'Row Header' at the system prompt System.out.print("Roll Not"); System.out.print("Namett"); System.out.print("Marks1tt"); System.out.print("Marks2tt"); System.out.print("Marks3tt"); System.out.println("Total"); // Retrieving records from the RecordSet rs and // displaying them at the system prompt // This code uses a column name to extract a // column value from the RecordSet while (rs.next()) { int r = rs.getInt(1); String n = rs.getString(2); int m1 = rs.getInt(3); int m2 = rs.getInt(4); int m3 = rs.getInt(5); int total = rs.getInt(6); System.out.print(r + "t"); System.out.print(n + "tt"); System.out.print(m1 + "tt"); System.out.print(m2 + "tt"); System.out.print(m3 + "tt"); System.out.println(total); } } } stmt.close( ); conn.close( ); } // End of try block catch(SQLException ex) { System.out.println("SQLException: " + ex); } // End of main() method // End of class PreparedStudent TRANSACTIONS 1. A group of statements form a transaction. 2. A transaction can be committed if all the statements in the group are executed successfully. If one statement in the group fails, the transaction can be rolled back as if none of the statements has been issued. Prof. Mukesh N. Tekwani Page 21 of 24
  • JDBC 3. Why should we group statements into a transaction? This is done for maintaining database integrity. E.g., in a banking environment, if money is transferred from one account to another, we must debit one account and simultaneously credit another account. If any one of these transactions cannot be executed the other should also not be executed. Thus, if a debit has taken place but the credit cannot take place, the debit statement should also be disallowed. 4. When statements are grouped in a transaction, then the transaction either succeeds in full and it can be committed or it fails somewhere and the transaction can be rolled back (like undo feature). This rollback will cancel all the updates to the database. 5. By default, a database connection is in autocommit mode. That is each SQL statement is committed to the database as soon as it is executed. Once a statement is committed, you cannot roll it back. We can turn off this default option as follows: conn.setAutoCommit(false) 6. Example: a. Create a Statement object as usual: Statement stat = conn.createStatement(); b. Call executeUpdate() any number of times, as follows: stat.executeUpdate(command1); stat.executeUpdate(command2); stat.executeUpdate(command3); : : c. If all statements have been executed successfully, call the commit method() as foolows: conn.commit(); d. But if any error has occurred, we can call the rollback() command as follws: conn.rollback(); Save Points: We can control the position upto which we want to rollback the commands. This is done by using save points. By creating a save point, we are marking points upto which we can later return without abandoning the entire transaction. Statement stat = conn.createStatement(); //start transaction; rollback goes here stat.executeUpdate(command1); Savepoint svpt = conn.setSavePoint(); // set save point, rollback(svpt) will go here stat.executeUpdate(command2); if ( . . . ) conn.rollback(svp); //undo effect of command 2 . . . conn.commit(); If a savepoint is no longer needed, we must release it as follows: conn.releaseSavepoint(svpt); STORED PROCEDURES 1. A stored procedure is a block of SQL code stored in the database and executed on the server. 2. The CallableStatement interface allows you to interact with them. Page 22 of 24 mukeshtekwani@hotmail.com
  • JDBC - 1 3. Working with CallableStatement objects is very similar to working with PreparedStatements. The procedures have parameters and can return either ResultSets or an update count. 4. Their parameters can be either input or output parameters. 5. Input parameters are set via the setXXX methods. 6. Stored procedures need to be supported by the database in order to use them. PROGRAMMING EXERCISES 1. Write a JDBC program to create a table GRTGS (Message – Text), insert two greetings into the table, display the table contents, and drop the table. Assume the DSN name is GREETINGS. 2. Write JDBC programs for the following: a. Create an AddressBook Table with the following fields: AddID (numeric), Name(Text), Email(Text) and PhoneNo. b. To insert 5 records in this table. c. To query this table – user enters the phone number and display the name and email id. d. To delete a record – user enters the phone number and delete record after confirmation. e. To modify (edit) a particular record. User enters a phone no, display the data, and take new input for all fields. Update the table with this new data. 3. Use JDBC API to do the following: • Create a table in Oracle with following structure. FriendName Text(20) Dob Date Details Text(20) PhoneNumber Number • Insert the records • Show all the records from the table. 4. Write a program that takes values for BookName and BookId from the user on command prompt and inserts the values in the table Book assuming table to be already created. 5. Write a program that retrieves the records from Book having field Book ,BookName and BookId 6. Write a program that searches for record in table BOOK(BookName varchar2(25),BID number(2,5)) .The value for the BookName is taken from command prompt ,if record found “Record Found” message is displayed and the details regarding the respective Book is displayed else “Record Not Found” is displayed. 7. Write a JDBC program that accepts a table name and displays the total number of records in it. 8. Write a JDBC program that prints the names of all columns in a table that is given on the command line. 9. Write a JDBC program to change the name of a column. Table name is supplied on command line. 10. Create a database “EMPLOYEEDB.MDB” through Microsoft Access. Create a Data Source Name (DSN); give an appropriate name for DSN. Then write a single program to create a table EMPLOYEE (ENO – Integer, ENAME-Text, BPAY-double, ALLOWANCES-double, TAX-double, NETPAYdouble). Through the same program insert 5 records, and display the output in a tabular manner. NETPAY must be calculated and entered in the table using the formula: NETPAY = BPAY + ALLOWANCES – TAX. 11. Write a program that accepts an employee number (ENO) for the above database and if it is found in the table, prints its details, else prints “Record not found”. 12. Write a JDBC program that accepts subject name on the command line and displays the highest mark scored in that subject. Use the table TYBSC that has been used in this chapter. 13. Modify (alter) the above table (EMPLOYEE) so that it contains one more column called DESIGNATION. Give appropriate SQL query to update this column. Then display all records where designation is “Manager”. Prof. Mukesh N. Tekwani Page 23 of 24
  • JDBC REVIEW QUESTIONS 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. What are the components of JDBC? Explain the three statement objects in JDBC Explain types of execute methods in JDBC with examples. Explain DriverManager class and its methods. What is DSN? How is it created? Explain steps for connectivity in JDBC Explain any 4 methods of PreparedStatement. Discuss the two-tier architecture for data access. Discuss the three-tier architecture for data access. What are its advantages over the two-tier architecture? Differentiate between Statement and PreparedStatement Explain different methods of ResultSet object. State the object which encapsulates the data retrieved from the database. State the method which is used to get the value of the specified column of the current row from a database. State the method which is used to get the value of the specified column of the current row from a database. Which method is used to execute a SELECT query? Which method is used to execute DDL statements such as INSERT, UPDATE, and DELETE? Write short notes on: a. JDBC b. JDBC-ODBC Bridge c. Types of driver managers in JDBC d. PreparedStatement e. Transaction and savepoint Explain the following method, and also state the class/interface to which they belong: • next() • close() • forName() • createStatement() • executeUpdate() • prepareStatement() • getConnection() • getString() • getColumnCount() JDBC PROGRAMS IN A NUTSHELL 1. Load the JDBC-ODBC Bridge Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 2. Connect to a data source: Connection conn = DriverManager.getConnection(URL, [username, password]); 3. Ask the connection object for a Statement object Statement stmt = conn.createStatement(); 4. Execute a SQL statement String createString = "create table SYBSc " + "(RollNo Number, NAME Text(25) Total Number)"; stmt.executeUpdate(createString); Page 24 of 24 mukeshtekwani@hotmail.com