Presentation is loading. Please wait.

Presentation is loading. Please wait.

Interacting with Database

Similar presentations


Presentation on theme: "Interacting with Database"— Presentation transcript:

1 Interacting with Database
Chapter 4 Interacting with Database Objectives : -> To create database driven business applications using the database API’s two tier and three tier models and the Java.Sql package

2 What is JDBC? JDBC (Java Database Connectivity)
Java JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc drivers to connect with the database.

3 Why use JDBC Before JDBC, ODBC API was the database API to connect and execute query with the database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language).

4 JDBC Architecture Two-tier and Three-tier Processing Models
The JDBC API supports both two-tier and three-tier processing models for database access.

5 Two-tier Architecture for Data Access

6 Two-tier Architecture for Data Access
A Java applet or application talks directly to the data source. JDBC drivers are used to communicate with the particular data source being accessed. User's commands are delivered to the database and the results of those statements are sent back to the user. The data source may be located on another machine to which the user is connected via a network. This is referred to as a client/server configuration, with the user's machine as the client, and the machine housing the data source as the server. The network can be an intranet, which, for example, connects employees within a corporation, or it can be the Internet.

7 Three-tier Architecture for Data Access

8 Three-tier Architecture for Data Access
In the three-tier model, commands are sent to a "middle tier" of services, which then sends the commands to the data source. The data source processes the commands and sends the results back to the middle tier, which then sends them to the user. The middle tier makes it possible to maintain control over access and the kinds of updates that can be made to corporate data. It also simplifies the deployment of applications.

9 JDBC Driver Types JDBC drivers are divided into four types which are as follows: 1) Type 1: JDBC-ODBC Bridge driver (Bridge) 2) Type 2: Native-API/partly Java driver (Native) 3) Type 3: All Java/Net-protocol driver (Middleware) 4)Type 4: All Java/Native-protocol driver (Pure)

10 Type 1 JDBC Driver JDBC-ODBC Bridge driver
-> The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver. -> ODBC is a generic API. -> The JDBC-ODBC Bridge driver is recommended only for experimental use or when no other alternative is available.

11 Advantage The JDBC-ODBC Bridge allows access to almost any database, since the database's ODBC drivers are already available. Disadvantages 1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable. 2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver, then to the database, and this applies even in the reverse process. They are the slowest of all driver types. 3. The client system requires the ODBC Installation to use the driver. 4. Not good for the Web.

12 Type 2 JDBC Driver Native-API/partly Java driver
Type 2 drivers convert JDBC calls into (native C/C++ API calls) database-specific calls i.e. this driver is specific to a particular database. Example: Oracle will have oracle native API.

13 Advantage Offer better performance than the JDBC-ODBC Bridge as the layers of communication (tiers) are less than that of Type 1 and also it uses Native API which is Database specific. Disadvantage 1. Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet.  2. Like Type 1 drivers, it’s not written in Java Language which forms a portability issue.  3. If we change the Database we have to change the native API as it is specific to a database

14 Type 3 JDBC Driver All Java/Net-protocol driver
Type 3 database requests are passed through the network to the middle-tier server. The middle-tier then translates the request to the database. The middle-tier server can in turn use Type1, Type 2 or Type 4 drivers.

15 Advantage 1. This driver is server-based, so there is no need for any vendor database library to be present on client machines. 2. This driver is fully written in Java and hence Portable. It is suitable for the web. 3. The net protocol can be designed to make the client JDBC driver very small and fast to load.  4. This driver is very flexible allows access to multiple databases using one driver. 5. They are the most efficient amongst all driver types. Disadvantage It requires another server application to install and maintain. Traversing the recordset may take longer, since the data comes through the backend server.

16 Type 4 JDBC Driver Native-protocol/all-Java driver
The Type 4 uses java networking libraries to communicate directly with the database server. This driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as thin driver. It is fully written in Java language.

17 Advantage This type of drivers are completely written in Java so it achieves platform independence and eliminate deployment administration issues. It is most suitable for the web.  Number of translation layers is very less i.e. type 4 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 also good.  No need to install special software on the client or server. 4. These drivers can be downloaded dynamically. Disadvantage With type 4 drivers, the user needs a different driver for each database.

18 DriverManager class It acts as an interface between user and drivers.
It keeps track of the drivers that are available and handles establishing a connection between a database and the appropriate driver. It also maintains a list of Driver classes that have registered themselves by calling the method DriverManager.registerDriver().

19 Commonly used methods of DriverManager class:
1) public static void registerDriver (Driver driver): It is used to register the given driver with DriverManager. 2) public static void deregisterDriver (Driver driver): It is used to deregister the given driver (drop the driver from the list) with DriverManager. 3) public static Connection getConnection(String url): It is used to establish the connection with the specified url. 4) public static Connection getConnection(String url,String userName,String password): It is used to establish the connection with the specified url, username and password.

20 Driver Interface Every databse driver needs to implement this interface. We can load as many databse drivers we want, but all of them must implement this interface. Each driver will provide a class implementing the Driver interface.  

21 Connection Interface java.sql.Connection interface represents a session between java application and database. All SQL statements are executed and results are returned within the context of a Connection object. Connection interface is mainly used to create java.sql.Statement, java.sql.PreparedStatement  and java.sql.CallableStatement objects For example : Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:DSN");

22 Statement Interface It provides methods to execute queries with the database. The statement interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.

23 Commonly used methods of Statement interface:
public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the object of ResultSet. public int executeUpdate(String sql): is used to execute specified query, it may be create, drop, insert, update, delete etc. public boolean execute(String sql): is used to execute queries that may return multiple results. public int[] executeBatch(): is used to execute batch of commands.

24 Steps to connect a Java Application to Database
The following 5 steps are the basic steps involve in connecting a Java application with Database using JDBC. 1) Register the Driver 2) Create a Connection 3) Create SQL Statement 4) Execute SQL Statement 5) Closing the connection

25 1) Register the Driver The forName() method of Class class is used to register the driver class. It dynamically loads the driver class into JVM. Syntax : public static void forName(String className) throws ClassNotFoundException   Example : Class.forName("oracle.jdbc.driver.OracleDriver"); Class.forName("Sun.Jdbc.Odbc.JdbcOdbcDriver");

26 2) Create a Connection Example :
The getConnection() method of Driver Manager class is used to create a connection. Syntax : 1) public static Connection getConnection(String url)throws SQLException   2) public static Connection getConnection(String url,String  name, String password) throws SQLException   Example : Connection con=DriverManager.getConnection (   Connection con=new DriverManager.getConnection (“Jdbc:Odbc:< dsn >", “username",“pswd");

27 3) Create SQL Statement The createStatement() method of Connection interface is used to create statement. The object of statement is responsible to execute queries with the database. Syntax : public Statement createStatement()throws  SQLException   Example : Statement stmt=con.createStatement();  

28 Interfaces and their uses
1) Statement It is used for general-purpose access to your database. They are useful when you are using static SQL statements at runtime. The Statement interface cannot accept parameters. 2)PreparedStatement It is used when you plan to use the SQL statements many times. The PreparedStatement interface accepts input parameters at runtime. 3)CallableStatement It is used when you want to access the database stored procedures. The CallableStatement interface can also accept runtime input parameters.

29 4) Execute SQL Statement
The executeQuery() method of Statement interface is used to execute queries to the database. This method returns the object of ResultSet that can be used to get all the records of a table. Syntax : public ResultSet executeQuery(String sql)throws SQLException  

30 Example : ResultSet rs = stmt. executeQuery ("select
Example : ResultSet rs = stmt.executeQuery ("select * from emp"); while(rs.next()) { System.out.println(rs.getInt(1)+" "+rs.getString(2)); }

31 Types of execute methods
Once you've created a Statement object, you can then use it to execute an SQL statement with one of its three execute methods. boolean execute (String SQL): Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. For eg. SQL DDL statements 2) int executeUpdate (String SQL): Returns the number of rows affected by the execution of the SQL statement. 3) ResultSet executeQuery (String SQL): Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a SELECT statement.

32 5) Closing the connection
After executing SQL statement you need to close the connection and release the session. The close()method of Connection interface is used to close the connection. Syntax : public void close() throws SQLException Example : con.close();

33 import java.sql.*; class odbcdemo { public static void main(String ar[]) try String url="jdbc:odbc:mydsn"; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // Register driver Connection c=DriverManager.getConnection(url); //Create connection object Statement st=c.createStatement(); // Create statement ResultSet rs=st.executeQuery("select * from emptable"); // Execute query while(rs.next()) System.out.println(rs.getInt(1)); System.out.println(rs.getString(2)); System.out.println(rs.getInt(3)); } catch(Exception e) System.out.println(e); } } }

34

35 import java. io. ; import java. sql
import java.io.*; import java.sql.*; class product { public static void main(String args[]) throws Exception ResultSet r; int x; Class. forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c=DriverManager.getConnection("jdbc:odbc:mydsn"); Statement s=c.createStatement(); String d[][]={{"Remote","TV","Mobile"}, {"101","102","103"}, {"20","10","15"}} ; s.execute("create table product (prod_name varchar(25), prod_id int, prod_quantity int)"); s.executeQuery("select * from product"); System.out.println("Table created"); c.close();

36 c=DriverManager.getConnection("jdbc:odbc:mydsn");
s=c.createStatement(); for(int i=0;i<3;i++) { s.executeUpdate("INSERT INTO product(prod_name,prod_id,prod_quantity)VALUES('"+ d[0][i]+"',"+d[1][i]+","+d[2][i]+")"); } r=s.executeQuery("select * from product"); while(r.next()) x=r.getInt("prod_id"); if (x==103) System.out.println("\nProduct Name:" + r.getString("prod_name") + "\t Product ID :" + x + "\t Product Quantity:" + r.getInt("prod_quantity"));

37


Download ppt "Interacting with Database"

Similar presentations


Ads by Google