Core jdbc basics

32
Core JDBC Basics Sourabrata Mukherjee

Transcript of Core jdbc basics

Page 1: Core jdbc basics

Core JDBC BasicsSourabrata Mukherjee

Page 2: Core jdbc basics

Topics:1.What is JDBC

2.Why Use JDBC and not ODBC?

3.JDBC Architecture

4.Steps to connect to the database using java

5.JDBC Driver and it’s Types

6.JDBC Connection

7.JDBC Statements

8.JDBC Result Sets

9.JDBC Transaction

10.Conclusion

Page 3: Core jdbc basics

JDBC and It’s Architecture●The JDBC (Java Database Connectivity) API defines interfaces and

classes for writing database applications in Java by making database connections. Using JDBC you can send SQL, PL/SQL statements to almost any relational database. JDBC is a Java API for executing SQL statements and supports basic SQL functionality. It provides RDBMS access by allowing you to embed SQL inside Java code.

Page 4: Core jdbc basics

Continue..●JDBC standardizes how to connect to a database, how to execute

queries against it, how to navigate the result of such a query, and how to execute updates in the database.

●Although JDBC was designed specifically to provide a Java interface to relational databases, you may find that you need to write Java code to access non-relational databases as well.

Page 5: Core jdbc basics

Why use JDBC and not ODBC?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).

* API (Application programming interface) is a document that contains description of all the features of a product or software. It represents classes and interfaces that software programs can follow to communicate with each other.

Page 6: Core jdbc basics

JDBC ArchitectureIn general, JDBC Architecture consists of two layers − JDBC API: This provides the application-to-JDBC Manager connection. JDBC Driver API: This supports the JDBC Manager-to-Driver Connection. The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases.

Page 7: Core jdbc basics

Steps to connect to the database using java

Register the driver class The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class.

Class.forName("com.mysql.jdbc.Driver");

Page 8: Core jdbc basics

Continue..Create the connection object The getConnection() method of

DriverManager class is used to establish connection with the database. Syntax of getConnection() method:

public static Connection getConnection(String url)throws SQLException

public static Connection getConnection(String url,String name,String password) throws SQLException

Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/SOURODB","root","souro");

Page 9: Core jdbc basics

Continue..Create the Statement object The createStatement() method of

Connection interface is used to create statement. The object of statement is responsible to execute queries with the database.

Statement stmt=con.createStatement();

Page 10: Core jdbc basics

Continue..Execute the query 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.

ResultSet rs=stmt.executeQuery("SELECT EmpID,LastName,FirstName,Address,City FROM EMPLOYEE");

Page 11: Core jdbc basics

Continue..Close the connection object By closing connection object statement

and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection.

con.close();

Page 12: Core jdbc basics

JDBC Driver and It’s TypesA JDBC driver is a collection of Java classes that enables you to connect to a certain database. For instance, MySQL will have its own JDBC driver. A JDBC driver implements a lot of the JDBC API interfaces. When your code uses a given JDBC driver, it actually just uses the standard JDBC interfaces. The concrete JDBC driver used is hidden behind the JDBC interfaces.

There are 4 types of JDBC drivers:

● JDBC-ODBC bridge driver

● Native-API driver

● Network Protocol driver

● Thin driver

Page 13: Core jdbc basics

Continue..JDBC-ODBC bridge driver - Uses ODBC driver to connect to the database. The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of thin driver.

Page 14: Core jdbc basics

Continue..Advantages:

●Easy to use.

●Can be easily connected to any database.

Disadvantages:

●Performance degraded because JDBC method call is converted into the ODBC function calls.

●The ODBC driver needs to be installed on the client machine.

Page 15: Core jdbc basics

Continue..Native-API driver - JDBC API calls are converted into native C/C++ API calls, which are unique to the database. These drivers are typically provided by the database vendors and used in the same manner as the JDBC-ODBC Bridge.

Page 16: Core jdbc basics

Continue..Advantage:

Performance upgrade than JDBC-ODBC bridge driver.

Disadvantage:

The Native driver needs to be installed on the each client machine. The Vendor client library needs to be installed on client machine.

Page 17: Core jdbc basics

Continue..Network Protocol driver - The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully written in java.

Page 18: Core jdbc basics

Continue..Advantage:

No client side library is required because of application server that can perform many tasks like auditing, load balancing, logging etc.

Disadvantages:

Network support is required on client machine.

Requires database-specific coding to be done in the middle tier.

Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to be done in the middle tier.

Page 19: Core jdbc basics

Continue..Thin driver - The thin 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.

Page 20: Core jdbc basics

Continue..Advantage:

Better performance than all other drivers. No software is required at client side or server side.

Disadvantage:

Drivers depends on the Database.

Page 21: Core jdbc basics

Continue..Which Driver should be used when?

If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is 4.

If your Java application is accessing multiple types of databases at the same time, type 3 is the preferred driver.

Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for your database.

The type 1 driver is not considered a deployment-level driver, and is typically used for development and testing purposes only.

Page 22: Core jdbc basics

JDBC ConnectionOnce a JDBC driver is loaded and initialized, you need to connect to the database. You do so by obtaining a Connection to the database via the JDBC API and the loaded driver. All communication with the database happens via a connection. An application can have more than one connection open to a database at a time. This is actually very common.

A Connection is the session between java application and database. The Connection interface is a factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object of Connection can be used to get the object of Statement and DatabaseMetaData. The Connection interface provide many methods for transaction management like commit(),rollback() etc.

Page 23: Core jdbc basics

JDBC StatementsA Statement is what you use to execute queries against the database. There are a few different types of statements you can use. Each statement corresponds to a single query.

Once a connection is obtained we can interact with the database. The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and properties that enable you to send SQL or PL/SQL commands

Page 24: Core jdbc basics

Continue..Each interface's purpose -

Interface Recommended Use

Statement Use for general-purpose access to your database. Useful when you are using static SQL statements at runtime. The Statement interface cannot accept parameters.

PreparedStatement Use when you plan to use the SQL statements many times. The PreparedStatement interface accepts input parameters at runtime.

CallableStatement Use when you want to access the database stored procedures. The CallableStatement interface can also accept runtime input parameters.

Page 25: Core jdbc basics

Continue..The important methods of Statement interface are as follows:

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.

Page 26: Core jdbc basics

JDBC Result SetsWhen you perform a query against the database you get back a ResultSet. You can then traverse this ResultSet to read the result of the query.

The object of ResultSet maintains a cursor pointing to a particular row of data. Initially, cursor points to before the first row.

But we can make this object to move forward and backward direction by passing either TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int) method

Page 27: Core jdbc basics

Continue..Commonly used methods of ResultSet interface -

public boolean next(): is used to move the cursor to the one row next from the current position.

public boolean previous(): is used to move the cursor to the one row previous from the current position.

public boolean first(): is used to move the cursor to the first row in result set object.

public boolean last(): is used to move the cursor to the last row in result set object.

public boolean absolute(int row): is used to move the cursor to the specified row number in the ResultSet object.

Page 28: Core jdbc basics

Continue..public boolean relative(int row): is used to move the cursor to the

relative row number in the ResultSet object, it may be positive or negative.

public int getInt(int columnIndex): is used to return the data of specified column index of the current row as int.

public int getInt(String columnName): is used to return the data of specified column name of the current row as int.

public String getString(int columnIndex): is used to return the data of specified column index of the current row as String.

public String getString(String columnName): is used to return the data of specified column name of the current row as String.

Page 29: Core jdbc basics

JDBC TransactionTransaction represents a single unit of work. The ACID properties describes the transaction management well. ACID stands for Atomicity, Consistency, isolation and durability.

Atomicity means either all successful or none.

Consistency ensures bringing the database from one consistent state to another consistent state.

Isolation ensures that transaction is isolated from other transaction.

Durability means once a transaction has been committed, it will remain so, even in the event of errors, power loss etc.

Page 30: Core jdbc basics

Continue..If your JDBC Connection is in autocommit mode, which it is by default, then every SQL statement is committed to the database upon its completion.

Transactions enable you to control if, and when, changes are applied to the database.

To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by default, use the Connection object's setAutoCommit() method. If you pass a boolean false to setAutoCommit( ), you turn off auto-commit. You can pass a boolean true to turn it back on again.

Page 31: Core jdbc basics

Conclusion

Page 32: Core jdbc basics

Thank You