jdbc database programming in java prepared by., mrs.s.amudha ap/swe

29
JDBC Database Programming in Java Prepared by., Mrs.S.Amudha AP/SWE

Upload: ethel-bishop

Post on 13-Dec-2015

234 views

Category:

Documents


1 download

TRANSCRIPT

JDBC Database Programming in Java

Prepared by.,

Mrs.S.Amudha AP/SWE

2

Agenda

• Overview of Databases and Java

• Overview of JDBC

• JDBC APIs

• Types of JDBC Drivers

• Other Database Techniques

3

Introduction

• JDBC is Java application programming interface that allows the Java programmers to access database management system from Java code.

• It was developed by JavaSoft, a subsidiary of Sun Microsystems.

• It is a java API which enables the java programs to execute SQL statements.

• JDBC provides methods for querying and updating the data in Relational Database Management system such as SQL, Oracle etc.

4

Introduction• In short JDBC helps the programmers to write

java applications that manage these three programming activities:

1. It helps us to connect to a data source, like a database.

2. It helps us in sending queries and updating statements to the database and

3. Retrieving and processing the results received from the database in terms of answering to your query.

5

Product Components of JDBCJDBC has four Components:

1. The JDBC API.• The JDBC application programming interface provides the facility for

accessing the relational database from the Java programming language

2. The JDBC Driver Manager.(Backbone)• The JDBC Driver Manager is a very important class that defines

objects which connect Java applications to a JDBC driver

3. The JDBC Test Suite.• The function of JDBC driver test suite is to make ensure that the

JDBC drivers will run user's program or not

4. The JDBC-ODBC Bridge.• The JDBC-ODBC bridge, also known as JDBC type 1 driver is a

database driver that utilize the ODBC driver to connect the database.

• This driver translates JDBC method calls into ODBC function calls

6

JDBC Architecture

7

JDBC Architecture

The JDBC API uses a Driver Manager and database-specific drivers to provide transparent connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access each data source. The Driver Manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases. The location of the driver manager with respect to the JDBC drivers and the servlet is shown in Figure

8

Layers of the JDBC Architecture

A JDBC driver translates standard JDBC calls into a network or database protocol or into a database library API call that facilitates communication with the database

9

Type 1 JDBC-ODBC Bridge• Type 1 drivers act as a "bridge"

between JDBC and another database connectivity mechanism such as ODBC.

• The JDBC- ODBC bridge provides JDBC access using most standard ODBC drivers.

• In this driver the java statements are converted to a jdbc statements.

• JDBC statements calls the ODBC by using the JDBC-ODBC Bridge

10

Type 2 Java to Native API• Type 2 drivers use the

Java Native Interface (JNI) to make calls to a local database library API.

• This driver converts the JDBC calls into a database specific call for databases such as SQL, ORACLE etc.

• This driver communicates directly with the database server.

• It requires some native code to connect to the database.

• Type 2 drivers are usually faster than Type 1 drivers.

11

Type 3 Java to Network Protocol Or All- Java Driver• Type 3 drivers are pure Java

drivers that use a proprietary network protocol to communicate with JDBC middleware on the server.

• The middleware then translates the network protocol to database-specific function calls.

• Type 3 drivers are the most flexible JDBC solution because they do not require native database libraries on the client and can connect to many different databases on the back end

12

Type 4 Java to Database Protocol• Type 4 drivers are pure Java

drivers that implement a proprietary database protocol (like Oracle's SQL*Net) to communicate directly with the database.

• Like Type 3 drivers, they do not require native database libraries and can be deployed over the Internet without client installation.

• One drawback to Type 4 drivers is that they are database specific.

13

JDBC Statements

• A JDBC statement object is used to send your SQL statement to the database server

• A JDBC statement is associated with an open connection and not any single SQL statement

• JDBC provides three classes of SQL statement– Statement– PreparedStatement – CallableStatement

14

Creating JDBC Statement

Statement stmt = con.createStatement();String createCS4400 = “Create table CS4400 “+ “(SSN Integer not null, Name VARCHAR(32),

“+ “Marks Integer)”;stmt.executeUpdate(createCS4400);String insertCS4400 = “Insert into CS4400

values “+“(123456789,abc,100)”;stmt.executeUpdate(insertCS4400);

15

Create JDBC Statement (contd..)

String queryCS4400 = “select * from CS4400”;ResultSet rs = Stmt.executeQuery(queryCS4400);While (rs.next()) {

int ssn = rs.getInt(“SSN”);String name = rs.getString(“NAME”);int marks = rs.getInt(“MARKS”);

}

Note: column number can also be used in place of column name.Refer to java.sql.ResulSet API for more details

16

Prepared Statement

• Unlike “Statement” it is given a SQL statement when it is created.

• Used when you want to execute “Statement” object many times

E.g String insert = “Insert into CS4400 (?,?,?)”;PreparedStatement stmt2 =

con.prepareStatement(insert);stmt2.setInt(1,123456789);stmt2.setString(2,abc);stmt2.setInt(3,100);stmt2.executeUpdate();

17

Prepared Statement (cont..)

• Executing Select Statemente.gString query =“SELECT Name from CS4400

where SSN=?”;PreparedStatement stmt2 =

con.prepareStatement(query);Stmt2.setInt(1,SSN);ResultSet rs = stmt2.executeUpdate();While (rs.next())

System.out.println(rs.getString(Name);

18

Callable Statement

• Used for executing stored procedures• ExampleString createProcedure = “Create Procedure

ShowGoodStudents” + “as Select Name from CS4400 where Marks > 90)”;

Stmt.executeUpdate(createProcedure);

CallableStatement cs = con.prepareCall(“(call ShowGoodStudents)”);

ResultSet rs = cs.executeQuery();

19

Basic steps in writing a JDBC Application

• JDBC Steps to be followed while writing JDBC program:

* Loading Driver

* Establishing Connection

* Executing Statements

* Getting Results

* Closing Database Connection

20

Loading Driver• Loading Database driver is very first step

towards making JDBC connectivity with the database.

• It is necessary to load the JDBC drivers before attempting to connect to the database.

• The JDBC drivers automatically register themselves with the JDBC system when loaded. Here is the code for loading the JDBC driver:

• Class.forName(driver).newInstance();

21

Establishing Connection• In the above step we have loaded the database driver to be

used.

• Now its time to make the connection with the database server.

• In the Establishing Connection step we will logon to the database with user name and password.

• Following code we have used to make the connection with the database:

con = DriverManager.getConnection(url+db, user, pass);

22

Executing Statements• In the previous step we established the

connection with the database, now its time to execute query against database.

• You can run any type of query against database to perform database operations.

• In this example we will select all the rows from employee table.

• Here is the code that actually execute the statements against database:

• ResultSet res = st.executeQuery( "SELECT * FROM employee" );

23

Getting Results• In this step we receives the result of execute statement.

In this case we will fetch the employees records from the recordset object and show on the console. Here is the code:

while (res.next()) {

String employeeName = res.getInt( " employee_name " );

System.out.println( employeeName );

}

24

Closing Database Connection• Finally it is necessary to disconnect from the database

and release resources being used.

• If you don’t close the connection then in the production environment your application will fail due to hanging database connections.

• Here is the code for disconnecting the application from database:

• con.close();

25

Creating a Database Tableimport java.sql.*;

public class CreateTable{

public static void main(String[] args) {

System.out.println("Table Creation Example!");

Connection con = null;

String url = "jdbc:mysql://localhost:3306/";

String dbName = "jdbctutorial";

String driverName = "com.mysql.jdbc.Driver";

String userName = "root";

String password = "root"; try{

Class.forName(driverName).newInstance();

con = DriverManager.getConnection(url+dbName, userName, password); try{

Statement st = con.createStatement();

String table = "CREATE TABLE Employee11(Emp_code integer, Emp_name varchar(10))";

st.executeUpdate(table);

System.out.println("Table creation process successfully!"); }

catch(SQLException s){ System.out.println("Table all ready exists!"); }

con.close(); }

catch (Exception e){ e.printStackTrace(); } } }

26

Transactions and JDBC• JDBC allows SQL statements to be grouped together into

a single transaction• Transaction control is performed by the Connection

object, default mode is auto-commit, I.e., each sql statement is treated as a transaction

• We can turn off the auto-commit mode with con.setAutoCommit(false);

• And turn it back on with con.setAutoCommit(true);• Once auto-commit is off, no SQL statement will be

committed until an explicit is invoked con.commit();• At this point all changes done by the SQL statements will

be made permanent in the database.

27

Handling Errors with Exceptions

• Programs should recover and leave the database in a consistent state.

• If a statement in the try block throws an exception or warning, it can be caught in one of the corresponding catch statements

• How might a finally {…} block be helpful here?

• E.g., you could rollback your transaction in a catch { …} block or close database connection and free database related resources in finally {…} block

28

JDBC references

• JDBC Data Access API – JDBC Technology Homepage– http://java.sun.com/products/jdbc/

index.html• JDBC Database Access – The Java Tutorial

– http://java.sun.com/docs/books/tutorial/jdbc/index.html

• JDBC Documentation– http://java.sun.com/j2se/1.4.2/docs/guide/

jdbc/index.html• java.sql package

– http://java.sun.com/j2se/1.4.2/docs/api/java/sql/package-summary.html

• JDBC Technology Guide: Getting Started– http://java.sun.com/j2se/1.4.2/docs/guide/

jdbc/getstart/GettingStartedTOC.fm.html• JDBC API Tutorial and Reference (book)

http://java.sun.com/docs/books/jdbc/• www.roseindia.net

29