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.

Slides:



Advertisements
Similar presentations
CE203 - Application Programming Autumn 2013CE203 Part 51 Part 5.
Advertisements

Java Database Connectivity (JDBC). 2/24 JDBC (Java DataBase Connectivity) - provides access to relational database systems JDBC is a vendor independent.
Basic JDBC Celsina Bignoli What is JDBC Industry standard for database- connectivity between the Java language and a wide range of.
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 JDBC Java Database Connectivity. 2 c.pdf
1 Lecture 29 More on JDBC Overview  Objectives of this lecture  JDBC and its Drivers  Connecting to Databases (Java’s Connection class)  Querying a.
JDBC Java API for Database Connectivity. Layout of this recitation Introduction to JDBC API JDBC Architecture Understanding the design of JDBC API –Classes.
UFCE4Y UFCE4Y-20-3 Components and Services Julia Dawson.
Java MS Access database connectivity Follow these steps: 1)Go to the start->Control Panel->Administrative Tools- > data sources. 2)Click Add button and.
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.
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.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 8 Object Oriented Programming in Java Advanced Topics Java Database.
Java Database Connectivity Vijayan Sugumaran Department of DIS Oakland University.
© Wang Bin 2004 JDBC ----Java Database Connectivity.
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.
Java Utility Classes CS 21b. Some Java Utility Classes Vector Hashtable StringTokenizer * import java.util.*;
CONTROLPANEL Java.sql package This package provides the APIs for accessing and processing data which is stored in the database especially relational.
JDBC Java and Databases, including Postgress. JDBC l Developed by Industry leaders l Three main goals: –JDBC should be an SQL-level API –JDBC should capitalize.
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.
1 JDBC Aum Amriteshwaryai Namah. 2 2 JDBC – Java DataBase Connectivity.
JDBC Enterprise Systems Programming. JDBC  Java Database Connectivity  Database Access Interface provides access to a relational database (by allowing.
COMP201 Java Programming Topic 15: Database Connectivity JDBC Reading: Chapter 4, Volume 2.
WEB/DB1 DATABASE PROGRAMMING 3JDBC by the ASU Scholars.
JDBC – Java Database Concentricity
Copyright  Oracle Corporation, All rights reserved. 6 Accessing a Database Using the JDBC API.
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.
Chapter 17 Accessing Databases with JDBC. JDBC JDBC provides a standard library for accessing relational databases. By using the JDBC API, you can access.
JDBC - Connection The programming involved to establish a JDBC connection is fairly simple. Here are these simple four steps − Import JDBC Packages: Add.
JDBC Database Programming in Java Prepared by., Mrs.S.Amudha AP/SWE.
JDBC CS 124. JDBC Java Database Connectivity Database Access Interface provides access to a relational database (by allowing SQL statements to be sent.
12/6/2015B.Ramamurthy1 Java Database Connectivity B.Ramamurthy.
Li Tak Sing COMPS311F. Database programming JDBC (Java Database Connectivity) Java version of ODBC (Open Database Connectivity) ODBC provides a standard.
Java and Databases. JDBC Architecture Java Application JDBC API Data Base Drivers AccessSQL Server DB2InformixMySQLSybase.
DATABASE CONNECTIVITY TO MYSQL. Introduction =>A real life application needs to manipulate data stored in a Database. =>A database is a collection of.
16 Java Database Connectivity. 2 Understand the JDBC Understand the steps of the JDBC: 1.) Importing packages 2.) Opening a connection to a database 3.)
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.
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.
Advanced Java Session 5 New York University School of Continuing and Professional Studies.
Database Programming With Java & JDBC Reading: DD Ch. 18, pp al/jdbc/index.html, or anything covering JDBC.
Umair Javed©2005 Enterprise Application Development Java Database Connectivity (JDBC) JDBC1.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Java Database Connectivity.
1 JDBC – Java Database Connectivity CS , Spring 2010.
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
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.
JDBC Statements The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and properties that enables to send SQL or PL/SQL.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java program to connect to any database.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
Interacting with Database
Lec - 14.
JDBC 15-Apr-18.
JDBC Database Management Database connectivity
JDBC – Java Database Connectivity
JDBC 21-Aug-18.
JDBC 15-Nov-18.
Interacting with Database
JDBC Example.
Presentation transcript:

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 the primary functions of opening and managing connections to a particular DBMS. The java.sql package contains the entire JDBC API that sends SQL (Structured Query Language) statements to relational databases and retrieves the results of executing those SQL statements. Important classes and interfaces of this package are: 1. DriverManager Class 2. Connection Interface 3. Statement Interface 4. PreparedStatement Interface 5. ResultSet Interface 6. ResultSetMetaData Interface

1. DriverManager Class It controls the interface between the application and a set of JDBC drivers. Provides set of methods for managing the drivers. Used to locate a suitable driver from amongst those loaded on the computer Methods – public static java.sql.Connection getConnection (String url, String user, String password) – it attempts to establish a connection to the specified database URL. If it is successful, it returns a Connection object, which represents a connection to the database. 2. Connection Interface A Connection object represents a connection with a database. In this SQL statements can be executed, returning resultsets. Methods – public abstract void close () - it provides for immediate release of the Connection’s database resource and JDBC resources. public abstract Statement createStatement () - it returns a new statement object that can be used to execute SQL statements.

3.Statement Interface The Statement object execute SQL statements that are static and obtain results following execution. Results are in the form of a ResultSet object. Methods- public abstract ResultSet executeQuery (String sql) – executes an SQL statement that returns a single ResultSet object. public abstract int executeUpdate (String sql) - executes SQL UPDATE, DELETE OR INSERT statements and return a row count. 4.PreparedStatement Interface It extends the Statement interface. If the application requires multiple execution of a particular SQL statement, it is pre-complied and stored in PreparedStatement object. This object can then be used many times to execute the statement efficiently. Methods – public abstract ResultSet executeQuery () – used to execute SQL statements. public abstract int executeUpdate () - executes SQL UPDATE, DELETE OR INSERT statements and do not return anything.

5. ResultSet Interface The data that is generated by the execution of a SQL statement is stored in, and can be accessed from a ResultSet object. It watches a single row of data at a time. This row of data is called its current row. When a SQL statement is re-executed the current ResultSet is automatically closed and a new RecordSet is created. Methods- public abstract void close () – is used when the application wants to release a ResultSet database resource and JDBC resource immediately public abstract String getString (String columnName) – gets the value of a column in the current row as Java String public abstract boolean next () – A ResultSet is initially positioned before its first row, the first call to the next makes the first row the current row, second call makes the second row the current row etc.

6. ResultSetMetaData Interface The ResultSetMetaData object returned by getMetaData() constructor provides access to information which indicates the number, type and properties of ResultSet columns. Methods – public abstract int getColumnCount () – method returns the number of columns in the ResultSet public abstract String getColumnName (int column) – method returns the name of the column public abstract String getTableName (int column) – returns the name of a table.

Java Database Connectivity Steps Before you can create a java jdbc connection to the database, you must first import the java.sql package. Following are steps that must be followed to establish a JDBC connection:- 1. Loading Driver 2. Establishing Connection 3. Creating a JDBC Statement object 4. Executing Statements and getting Results 5. Closing Database Connection

Loading a Driver It is necessary to load the JDBC drivers before attempting to connect to the database. In this step of the jdbc connection process, we load the driver class by calling Class.forName() with the Driver class name as an argument. This method dynamically load the driver's class file into memory, which automatically registers it. This method is preferable because it allows user to make the driver registration configurable and portable. Once loaded, the Driver class creates an instance of itself. A client can connect to Database Server through JDBC Driver. The following example uses Class.forName( ) to register the Oracle driver: try { Class.forName ("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { System.out.println ("Error: unable to load driver class!"); }

Establishing Connection The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. Its getConnection() method is used to establish a connection to a database. It uses a username, password, and a jdbc url to establish a connection to the database and returns a connection object. A jdbc Connection represents a session/connection with a specific database. Within the context of a Connection, SQL, PL/SQL statements are executed and results are returned. An application can have one or more connections with a single database, or it can have many connections with different databases. A Connection object provides metadata i.e. information about the database, tables, and fields. try { Connection dbConnection=DriverManager.getConnection (url,”loginName”,”Password”) ; } catch( SQLException x ) { System.out.println( “Couldn’t get connection!” ); }

Creating a JDBC Statement object Once a connection is obtained we can interact with the database. Connection interface defines methods for interacting with the database via the established connection. To execute SQL statements, user need to instantiate a Statement object from connection object by using the createStatement() method. Example : Statement statement = dbConnection.createStatement(); A statement object is used to send and execute SQL statements to a database. Three kinds of Statements 1. Statement: Execute simple sql queries without parameters. Statement createStatement()- Creates an SQL Statement object. 2.Prepared Statement: Execute precompiled sql queries with or without parameters. PreparedStatement prepareStatement(String sql)- returns a new PreparedStatement object. PreparedStatement objects are precompiled SQL statements. 3.Callable Statement: Execute a call to a database stored procedure. CallableStatement prepareCall(String sql)- returns a new CallableStatement object. CallableStatement objects are SQL stored procedure call statements

Executing Statements Statement interface defines methods that are used to interact with database via the execution of SQL statements. The Statement class has three methods for executing statements: executeQuery(), executeUpdate(), and execute(). For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate(). ResultSet provides access to a table of data generated by executing a Statement. The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The next() method is used to successively step through the rows of the tabular results. ResultSetMetaData Interface holds information on the types and properties of the columns in a ResultSet. It is constructed from the Connection object.

Closing JDBC connections At the end of your JDBC program, it is required explicitly close all the connections to the database to end each database session. However, if you forget, Java's garbage collector will close the connection when it cleans up stale objects. Relying on garbage collection, especially in database programming, is very poor programming practice. To ensure that a connection is closed, user could provide a finally block in code. A finally block always executes, regardless if an exception occurs or not. To close above opened connection you should call close() method as follows: dbconnection.close();

Connectivity Model Java Application The user Interface 32-bit ODBC Access Driver The Access Database and Its Table Java’s Driver Manager, Responsible for setting up the JDBC-ODBC bridge

Using Java’s Driver Manager to Connect to the Database Java Driver Manger ODBC System DSN The Access Database, table, With data in it. Creates a Connection Object, which communicates with the ODBC driver and in turn spawns a ResultSet object to hold the record set returned by the query made to the database table. The ResultSet Object This holds the records retrieved from the Access Database table

Navigating through Multiple Rows retrieved from a Database ResultSets are composed of rows of data. The table rows are retrieved in sequence. Intially, A ResultSet maintains a cursor pointing to it first row of data. The ResultSet.next() method is used to successively step through the rows of the tabular results. It returns false, when there are no more rows to navigate to in the ResultSet. Example- ResultSet rs = statement.executeQuery(“SELECT * from emp”); rs.next(); Extraction of values from the current row is possible in two ways: 1. Accessing columns of the current row by index number 2. Accessing columns of the current row by name.

Methods used to retrieve values from database The current row’s content are accessible via getXxx() method of the ResultSet Interface. Some of these methods are :- public abstract boolean getBoolean (String columnName) public abstract boolean getBoolean (int columnIndex) public abstract boolean getFloat (String columnName) public abstract boolean getFloat (int columnIndex) public abstract boolean getDouble (String columnName) public abstract boolean getDouble (int columnIndex) public abstract boolean getInt (String columnName) public abstract boolean getInt (int columnIndex) public abstract boolean getLong(String columnName) public abstract boolean getLong(int columnIndex) public abstract boolean getString(String columnName) public abstract boolean getString(int columnIndex)

import java.sql.*; public class jdbcodbc { public static void main(String args[]) { Connection con = null; Statement st = null; ResultSet rs = null; String url = "jdbc:odbc:java"; String db = "student"; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection(url) ; System.out.println("connection ok"); st = con.createStatement(); String sql = "select * from stud";

rs = st.executeQuery(sql); System.out.println("Id\tName\tMarks"); while (rs.next()) { System.out.print(rs.getInt(1)); System.out.print("\t "+rs.getString(2)); System.out.print("\t "+rs.getInt(3)); System.out.print("\t "+rs.getInt(4)); System.out.println("\t "+rs.getInt(5)); } rs.close(); st.close(); con.close(); } catch (Exception e) { System.out.println(e); } }

Popular JDBC driver names and database URL RDBMS JDBC driver nameURL format MySQLcom.mysql.jdbc.Driverjdbc:mysql://hostname/ databaseName ORACLE Number:databaseName DB2COM.ibm.db2.jdbc.net.DB2Driverjdbc:db2:hostname:port Number/databaseName