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.

Slides:



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

Copyright  Oracle Corporation, All rights reserved. 2 Java and Databases: An Overview.
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.
1 C. Shahabi Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California
1 Lecture 29 More on JDBC Overview  Objectives of this lecture  JDBC and its Drivers  Connecting to Databases (Java’s Connection class)  Querying a.
CSE470 Software Engineering Fall Database Access through Java.
JDBC Java API for Database Connectivity. Layout of this recitation Introduction to JDBC API JDBC Architecture Understanding the design of JDBC API –Classes.
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.
Helena Pomezná, ciz034 St. skupina: L392 FEI, VŠB-TUO Ak. rok. 2002/2003 Download:
Java Database Connectivity Vijayan Sugumaran Department of DIS Oakland University.
© Wang Bin 2004 JDBC ----Java Database Connectivity.
CSE470 Software Engineering Fall Database Access through Java.
Beginning Databases with JDBC Mike Bradley Adapted from and notes by Kevin Parker, Ph.D.
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.
Database Programming in Java Corresponds with Chapter 32, 33.
Dr R R DOCSIT, Dr BAMU. Basic Java : Introduction to JDBC 2 Objectives of This Session State what is Java Database Connectivity State different.
JDBC (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
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. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.
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 (JDBC). Topics 1. The Vendor Variation Problem 2. SQL and Versions of JDBC 3. Creating an ODBC Data Source 4. Simple Database.
Copyright © 2002 ProsoftTraining. All rights reserved. Building Database Client Applications Using JDBC 2.0.
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.
JDBC CS 124. JDBC Java Database Connectivity Database Access Interface provides access to a relational database (by allowing SQL statements to be sent.
JDBC CHAPTER-2. JDBC - Java Database Connectivity. JDBC from Sun Microsystems provides API or Protocol to interact with different databases. With the.
12/6/2015B.Ramamurthy1 Java Database Connectivity B.Ramamurthy.
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–
1 Session 2 Module 3: Scrollable Resultset and Rowsets.
DATABASE CONNECTIVITY TO MYSQL. Introduction =>A real life application needs to manipulate data stored in a Database. =>A database is a collection of.
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.
Database Access Using JDBC BCIS 3680 Enterprise Programming.
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.
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.
Advanced Java Session 5 New York University School of Continuing and Professional Studies.
Ch. NoNameMarks 01AWT24 02Networking18 03JDBC20 04Swing18 05Servlet20 Advance Java Programming.
Database Programming With Java & JDBC Reading: DD Ch. 18, pp al/jdbc/index.html, or anything covering JDBC.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Java Database Connectivity.
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
Interacting with Database
ODBC, OCCI and JDBC overview
JDBC Database Management Database connectivity
Introduction to Programming with Java
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
Java API for Database Connectivity
JDBC Example.
Presentation transcript:

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 information in a hierarchical, vertical manner. In Swing, we this is accomplished this with the use of the JTree class. To display data in a tabular form we can make use of the JTable class in Swing. JProgressBar class is implemented to display graphical progress of a the task. Swing components work within the Model View Controller (MVC) model.

Java Simplified / Session 30 / 3 of 33 Review Contd… Characteristics common to all Swing components are content, visual appearance and behavior. The MVC model contains a set of classes and user interfaces for various platforms, which help in changing the “look and feel” of the component. KeyStroke handling, action objects, nested containers, virtual desktops, compound borders, drag and drop, Java 2D, customized dialogs, standard dialog classes and generic undo capabilities are some of the special features of Swing.

Java Simplified / Session 30 / 4 of 33 Objectives Explain the concept of database connectivity Describe ODBC Discuss what is JDBC Discuss why we need JDBC Describe the java.sql package in brief Discuss types of drivers Explain the anatomy of a JDBC program

Java Simplified / Session 30 / 5 of 33 Database A database contains data that is in an organized form. Client/Server applications make extensive use of database programming. Activities may involve opening a connection, communicating with a database, executing SQL statements and retrieving query results. Standardized APIs are available that simplify database programming. Examples of these are ODBC and JDBC.

Java Simplified / Session 30 / 6 of 33 ODBC Open DataBase Connectivity (ODBC) is an Application Programming Interface (API) provided by Microsoft for accessing databases. It uses Structured Query Language or SQL as its database language. Provides functions to insert, modify and delete data and obtain information from the database.

Java Simplified / Session 30 / 7 of 33 Task The following tasks are performed within an application that uses ODBC: Establish a connection with the database. Send the SQL statement to the data source. Define the storage area to store the result set and also the data type of the result set. Trace errors if any and process them. Get the results. Control the transactions. Terminate the connection.

Java Simplified / Session 30 / 8 of 33 How ODBC connection takes place?  Application could be a GUI program  Makes use of ODBC to interact with databases  Driver Manager is part of Microsoft ODBC and is used to manage various drivers in the system  Driver implements the ODBC functions that are not supported by the DBMS software. Application ODBC Interface Driver Manager Access Driver Oracle Driver … Access Database Oracle Database …

Java Simplified / Session 30 / 9 of 33 JDBC JDBC is a Java Database Connectivity API that is a part of the Java Enterprise API. Defines a set of API objects and methods to interact with databases. JDBC is a must for all Java applications that access data stored in external data providers like SQL Server, Oracle or Access.

Java Simplified / Session 30 / 10 of 33 Need for JDBC ODBC uses a C interface that has lot of drawbacks in areas of security, implementation and so on. A literal translation of the ODBC C interface into a Java API would not be desirable. ODBC mixes simple and advanced features together and has complex options even for simple queries. A Java API like JDBC is needed in order to enable a “pure Java” solution. JDBC is portable. JDBC is a standard interface for Java programmers to access relational databases.

Java Simplified / Session 30 / 11 of 33 JDBC - ODBC bridge Database Server SQL Server JDBC Driver Types Database Server Oracle ODBC Driver DB-client JDBC-ODBC Bridge plus ODBC Driver ODBC is not readily convertible to Java as it is a C interface to Database Management System (DBMS). Sun provides a bridge driver to access ODBC data sources from JDBC. This is called the JDBC-ODBC Bridge plus ODBC driver. Major limitations of using JDBC-ODBC bridge is that the JDBC driver’s capabilities depend on the capabilities of the ODBC driver.

Java Simplified / Session 30 / 12 of 33 JDBC Driver Types Contd… Database Server JDBC Driver (Java and Binary Code) Vendor Specific Protocol DB-client Native API partly-Java Driver JDBC calls are converted into calls on the client API for DBMS. This driver uses JavaNativeInterface(JNI) that calls the local database APIs. The Native APIs partly-Java driver calls the Native Database Library that accesses the database. This driver like the ODBC driver needs binary code on the client machine. This driver also requires the native database libraries to be installed and configured on the client’s machine.

Java Simplified / Session 30 / 13 of 33 JDBC Driver (Pure Java Driver) Database Server SQL Server DB-client Networking protocol & middleware JDBC Driver Types Contd… Database Server JDBC-Net pure Java driver Uses a networking protocol and middleware to communicate with the server. Server then translates the messages communicated to DBMS specific function calls. Specific protocol used depends on the vendor. No need for client installation. Allows access to multiple back-end databases.

Java Simplified / Session 30 / 14 of 33 JDBC Driver Types Contd… Database Server JDBC Driver (Pure Java Driver) Vendor Specific Protocol DB-client Native-protocol pure Java driver 100% Java enabled and does not use CLI libraries. Capable of communicating directly with the database. Converts JDBC calls into network protocols such as TCP/IP and other proprietary protocols used by DBMS directly. Since many of these protocols are proprietary, the database vendors themselves will be the primary source of usage.

Java Simplified / Session 30 / 15 of 33 JDBC architecture Java Program JDBC Driver Application Server Database SQL commandResults

Java Simplified / Session 30 / 16 of 33 JDBC architecture Contd… Application Layer – developer makes calls to database through SQL and retrieves results. Driver layer – handles all communication with a specific driver implementation. It is responsible for developing code that acts as an interface to the database and supports the JDBC Application level calls. Four main Java interfaces that every Driver layer must implement are : Driver, Connection, Statement and ResultSet The JDBC API interface comprises of two layers:

Java Simplified / Session 30 / 17 of 33 JDBC architecture Contd… Application layer Driver layer Driver StatementResultSet Connection Implements Interfaces

Java Simplified / Session 30 / 18 of 33 JDBC components Application – here the JDBC methods are used to execute SQL statements and get results. Driver Manager – to load specific drivers for an user application. The following tasks are performed by this component: Locate the driver for a specific database. Process the initialization calls for JDBC Driver Data Source – User application interacts with this to get results.

Java Simplified / Session 30 / 19 of 33 java.sql package Contd… JDBC API defines a set of interfaces and classes used for communicating with the database. These are contained in the java.sql package. Classes included in this package are : Date, DriverManager, DriverPropertyInfo, Time, TimeStamp, Types Interfaces included are : Callable Statement, Connection, DatabaseMetaData, Driver, PreparedStatement, ResultSet, ResultSetMetaData, Statement

Java Simplified / Session 30 / 20 of 33 java.sql package Contd… The exceptions defined by the java.sql package are: DataTruncation SQLException (java.sql) SQLWarning (java.sql) BatchUpdateException

Java Simplified / Session 30 / 21 of 33 Creating a JDBC application Begin Import the java.sql package Load and Register the driver Create a Connection object Create a Statement object Execute the statement Close ConnectionEnd Close Resultset object Close Statement object

Java Simplified / Session 30 / 22 of 33 Example import java.sql.*; import java.util.*; class Jdbctest { public static void main(String args[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException ce) { System.out.println(ce); } try { String url = "jdbc:odbc:test"; Connection con = DriverManager.getConnection(url); Statement s = con.createStatement(); ResultSet rs = s.executeQuery("select * from friends"); while(rs.next()) { System.out.print(rs.getString(1)+"\t"); System.out.print(rs.getString(2)+"\t"); System.out.print(rs.getInt(3) + "\t"); System.out.print(rs.getDate(4) + "\t"); System.out.println(" "); } catch(SQLException ce) { System.out.println(ce); } Output

Java Simplified / Session 30 / 23 of 33 Using SQL The executeQuery() method of statement interface is used to execute a query. It takes an sql query string as an argument and returns the ResultSet containing the data. To retrieve the name, phone, and phone number from the table colleagues, the query to be written in JDBC is: String str = “ SELECT name, , phone FROM colleagues”; Statement stmt = con.createStatement(); ResultSet rset = stmt.executeQuery(str); The query statement to find out the number of employees who joined together on the same day and whose job_id is equal to 5 is: SELECT count(*) FROM Employee WHERE job_id=5 GROUP BY hire_date

Java Simplified / Session 30 / 24 of 33 Using SQL Contd… SQL statements that update the database do not return the results as ResultSets. Instead they return an integer representing the number of rows affected. Assume we need to add a new record. Then sql command in JDBC will be: String str = “INSERT into COFFEE VALUES(‘French_Roast’,00049,8.99,0,0) ”; Statement stmt = con.createStatement(); int rowcount = stmt.executeUpdate(str);

Java Simplified / Session 30 / 25 of 33 Example import java.sql.*; import java.util.*; class Jdbctest3 { public static void main(String args[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException ce) { System.out.println(ce); } try { String url = "jdbc:odbc:test"; String str = "INSERT INTO friends(name,address,salary)" +"VALUES('Jessica','Alaska',25690)"; Connection con = DriverManager.getConnection(url); Statement s = con.createStatement(); int rowcount = s.executeUpdate(str); String str1 ="select name, avg(salary) from friends" +" group by name"; ResultSet rs = s.executeQuery(str1); while(rs.next()) { System.out.print(rs.getString(1) +"\t" ); System.out.print(rs.getInt(2) +"\t" ); System.out.println(" "); } catch(SQLException ce) { System.out.println(ce); } Output

Java Simplified / Session 30 / 26 of 33 Using SQL Contd… The LIKE operator is used with SQL statements to compare two strings SELECT * FROM employee WHERE emp_id LIKE ‘A%’ Data Definition Language statements are used to create tables, add columns to the existing tables; delete tables and so on CREATE TABLE Emp(emp_name VARCHAR(25),emp_no VARCHAR(4),emp_age number);

Java Simplified / Session 30 / 27 of 33 Example import java.sql.*; import java.util.*; class Jdbc2 { public static void main(String args[]) { Connection con; Statement stmt; String url; String sql; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException ce) { System.out.println(ce); } try { url = "jdbc:odbc:test"; con = DriverManager.getConnection(url); sql = "Delete from friends where rtrim(name) like \'Kim\';"; System.out.println(" "); stmt = con.createStatement( ); stmt.executeUpdate(sql);

Java Simplified / Session 30 / 28 of 33 Example Contd… System.out.println("Record for Kim has been deleted"); con.close(); con = DriverManager.getConnection(url); sql = "Update friends set city=\'Adelaide\' where "+ "rtrim(name) like \'Mike\'; "; System.out.println(" "); stmt = con.createStatement(); stmt.executeUpdate(sql); con.close(); System.out.println("Record for Mike updated"); } catch(SQLException ce) { System.out.println(ce); } Output

Java Simplified / Session 30 / 29 of 33 Types of ResultSets Result sets may be scrollable or non scrollable. The three types of result set which are available are: TYPE_FORWARD_ONLY: The cursor will move forward only. TYPE_SCROLL_INSENSITIVE: The cursor can move forward or backward and also can be moved to a particular row relative to the current position. TYPE_SCROLL_SENSITIVE: It is same as the previous but with the difference is that if any changes are made to the database then the new values are visible.

Java Simplified / Session 30 / 30 of 33 Example import java.sql.*; import java.util.*; class JdbctestReverse { public static void main(String args[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException ce) { System.out.println(ce); } try { String url = "jdbc:odbc:test"; Connection con = DriverManager.getConnection(url); Statement s = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = s.executeQuery("select * from friends"); rs.afterLast(); while(rs.previous()) { System.out.print(rs.getString(1)+"\t"); System.out.print(rs.getString(2)+"\t"); System.out.print(rs.getInt(3) + "\t"); System.out.print(rs.getDate(4) + "\t"); System.out.println(" "); } catch(SQLException ce) { System.out.println(ce); } Output

Java Simplified / Session 30 / 31 of 33 Summary ODBC is a widely used API provided by Microsoft to help dealing with databases It uses SQL as its language and provides functions to insert, modify and delete data. The driver manager is part of Microsoft ODBC and is used to manage various drivers in the system. The driver is the actual software component that interacts with the databases and they are software specific such as SQL Server Driver, Ms Access Driver etc. JDBC is a Java Database Connectivity API that is a part of the Java Enterprise APIs provided by Sun Microsystems.

Java Simplified / Session 30 / 32 of 33 Summary Contd… JDBC defines a set of API objects and methods to interact with databases The JDBC classes are present in the java.sql package and all Java programs that need to interact with databases use methods from this package. We load the driver into the Java interpreter using the Class.forName() method Then, we establish a connection using the getConnection() method of DriverManager class. Next we use the createStatement() method of the Connection object. And finally we construct and execute SQL statements through the statement instance by using either executeQuery() or executeUpdate() methods

Java Simplified / Session 30 / 33 of 33 Summary Contd… It is possible to execute all sorts of Data Manipulation Language statements of SQL such as Create, Update through the statement instance. ResultSet can be scrollable or non scrollable.