Interacting with Database

Slides:



Advertisements
Similar presentations
Connecting to Databases. relational databases tables and relations accessed using SQL database -specific functionality –transaction processing commit.
Advertisements

Java Database Connectivity (JDBC). 2/24 JDBC (Java DataBase Connectivity) - provides access to relational database systems JDBC is a vendor independent.
Database programming in Java An introduction to Java Database Connectivity (JDBC)
JDBC - Java Database Connectivity The objectives of this chapter are: To describe the architecture of JDBC To outline the classes in the java.sql package.
Distributed Application Development B. Ramamurthy.
15-Jun-15 JDBC. JDBC is a Sun trademark It is often taken to stand for Java Database Connectivity Java is very standardized, but there are many versions.
1 C. Shahabi Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California
Java Database Connectivity (JDBC) java.sql package to query and update the database. JDBC is an API that allows java to communicate with a database server.
JDBC Java API for Database Connectivity. Layout of this recitation Introduction to JDBC API JDBC Architecture Understanding the design of JDBC API –Classes.
Objectives Describe JDBC Describe JDBC Driver Types
JDBC / ODBC JDBC is the java API that facilitate interaction of a java application with the DBMS. FIRST APPROACH:
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Getting connected.  Java application calls the JDBC library.  JDBC loads a driver which talks to the database.  We can change database engines without.
Java Database Connectivity (JDBC) Francisco Pajaro Saul Acosta Nahum Quezada Manuel Rubio.
1 Java Database Connection (JDBC) There are many industrial-strength DBMS's commercially available in the market. Oracle, DB2, and Sybase are just a few.
Java Database Connectivity Vijayan Sugumaran Department of DIS Oakland University.
© Wang Bin 2004 JDBC ----Java Database Connectivity.
Java Database Connectivity (JDBC) Introduction to JDBC JDBC is a simple API for connecting from Java applications to multiple databases. Lets you smoothly.
Java Database Connectivity ASE. Java Database Connectivity (JDBC) l JDBC – provides an interface to Relational Data Sources l JDBC library provides the.
What is JDBC? Java Database Connectivity (JDBC) is an API for the Java programming language that defines how a client may access a database. provides.
1 Java DataBase Connectivity JDBC java.sql.*. 2 Java DataBase Connectivity Draft release of JDBC spec (3/96) Java API for executing SQL statements (Since.
Dr R R DOCSIT, Dr BAMU. Basic Java : Introduction to JDBC 2 Objectives of This Session State what is Java Database Connectivity State different.
VICTORIA UNIVERSITY OF WELLINGTON Te Whare Wananga o te Upoko o te Ika a Maui COMP 302 Database Systems Java Data Base Connectivity Lecturer Dr Pavle Mogin.
Connecting to Oracle using Java November 4, 2009 David Goldschmidt, Ph.D. David Goldschmidt, Ph.D.
Introduction to JDBC Michelle Lee, Ye Wu & Jeff Offutt SWE 432 Design and Implementation of Software for the Web.
JDBC. JDBC stands for Java Data Base Connectivity. JDBC is different from ODBC in that – JDBC is written in Java (hence is platform independent, object.
JDBC  The JDBC (Java Database Connectivity) API helps a Java program to access a database in a standard way  JDBC is a specification that tells the.
JDBC – Java DataBase Connectivity. JDBC API Overview JDBC is Java API that allows the Java programmers to access database management system from Java.
JDBC Enterprise Systems Programming. JDBC  Java Database Connectivity  Database Access Interface provides access to a relational database (by allowing.
Accessing Database using JDBC. JDBC Objectives Gain basic knowledge of Java JDBC Become familiar with the basics of interacting with a database using.
COMP201 Java Programming Topic 15: Database Connectivity JDBC Reading: Chapter 4, Volume 2.
WEB/DB1 DATABASE PROGRAMMING 3JDBC by the ASU Scholars.
Java Database Connectivity. Java and the database Database is used to store data. It is also known as persistent storage as the data is stored and can.
JDBC Database Programming in Java Prepared by., Mrs.S.Amudha AP/SWE.
JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.
Session 30 Basics of JDBC. Java Simplified / Session 30 / 2 of 33 Review A Swing menu consists of a menubar, menuitems and menus. Trees are used to depict.
JDBC CHAPTER-2. JDBC - Java Database Connectivity. JDBC from Sun Microsystems provides API or Protocol to interact with different databases. With the.
Java and Databases. JDBC Architecture Java Application JDBC API Data Base Drivers AccessSQL Server DB2InformixMySQLSybase.
UNIT III - JDBC JDBC Overview – JDBC implementation – Connection class – Statements - Catching Database Results, handling database Queries. Networking–
JDBC and SQLJ CIS 612 Spring JDBC JDBC is an API that enables database access from Java programs JDBC for DB access provides ◦ Portability across.
JDBC CS 260 Database Systems. Overview  Introduction  JDBC driver types  Eclipse project setup  Programming with JDBC  Prepared statements  SQL.
CSI 3125, Preliminaries, page 1 JDBC. CSI 3125, Preliminaries, page 2 JDBC JDBC stands for Java Database Connectivity, which is a standard Java API (application.
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
Basics of JDBC Session 14.
JDBC Chapter 1 JDBC Introduction
JDBC - Java Database Connectivity. JDBC provides Java applications with access to most database systems via SQL The architecture and API closely resemble.
Ch. NoNameMarks 01AWT24 02Networking18 03JDBC20 04Swing18 05Servlet20 Advance Java Programming.
6-1 JAVA DATABASE CONNECTOR Colorado Technical University IT420 Tim Peterson.
Java and database. 3 Relational Databases A relational Database consists of a set of simple rectangular tables or relations The column headings are.
DEPTT. OF COMP. SC & APPLICATIONS
Note: To complete the examples in this section you need access to a database!! Most of the examples work for any database with JDBC drivers. However, connecting.
JDBC 15-Apr-18.
ODBC, OCCI and JDBC overview
JDBC Database Management Database connectivity
JDBC 21-Aug-18.
JDBC(Java Database Connectivity
Introduction to Programming with Java
Chapter 16 JAVA DATABASE CONNECTIVITY
JDBC 15-Nov-18.
Objectives In this lesson, you will learn about:
Mr. Harish Sharma Asst. Professor Dept. of CA & IT SGRRITS Dehradun
Interacting with Database
JDBC – ODBC DRIVERS.
Java Database Connectivity
JAVA DATABaSE CONNECTIVITY
ODBC and JDBC.
Java API for Database Connectivity
JDBC Example.
Presentation transcript:

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

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.

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).

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

Two-tier Architecture for Data Access

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.

Three-tier Architecture for Data Access

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.

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)

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.

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.

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.

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

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.

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.

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.

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.

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().

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.

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.  

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");

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.

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.

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

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");

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 (   "jdbc:oracle:thin:@localhost:1521:xe","system","password");   Connection con=new DriverManager.getConnection (“Jdbc:Odbc:< dsn >", “username",“pswd");

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();  

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.

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  

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)); }

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.

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();

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); } } }

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();

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"));