Java Database Connectivity
Java Database Connectivity
Java Database Connectivity
Amit Sharma
JDBC
Introduction
A RDBMS is usually the primary data resource in an enterprise application. The JDBC API provides developers with a way to connect to relational data from within Java code. Using the JDBC API, developer can create a client that can connect to a database, execute SQL statements, and processes the result of those statements.
Amit Sharma JDBC Rapid Application Development-CS3011
Introduction
JDBC helps you to write java applications that manage these three programming activities:
1. Connect to a data source, like a database 2. Send queries and update statements to the database 3. Retrieve and process the results received from the database in answer to your query In a package called java.sql, JDBC consists of a set of class files.
Amit Sharma JDBC Rapid Application Development-CS3011
JDBCODBC
The ODBC class of databases are a subset of ANSI SQL-2 databases. It is a standard proposed by Microsoft.
In Computing, Open Database Connectivity (ODBC) provides a standard software API method for using DBMSs.
The designers of ODBC aimed to make it independent of programming languages, database systems, and Operating systems.
Amit Sharma
JDBC
JDBCODBC Bridge
Java soft in a join effort with Intersolv that created an implementation of the java.sql interface which is designed to allow access to ODBC databases in order to get JDBC. There is an ODBC driver for each type of database. In addition, the application talks to a particular database through the ODBC driver manager. The driver manager translates between the application and the ODBC driver and the ODBC driver translates between the driver manager and the particular database.
Amit Sharma
JDBC
JDBC Architecture
ResultSet
Statement
ResultSet
PreparedStatement
ResultSet
CallableStatement
Connection
Driver Manager JDBC ODBC Bridge ODBC Driver
Oracle Database
JDBC Drivers
Driver must be registered with the JDBC DriverManager, before using Driver. This is done by using Class.forName() method, as
try {
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); //Class.forName(com.oracle.jdbc.OracleDriver); } catch (ClassNotFoundException ce) { // Handle exception }
ODBC
DB Client Lib
DB Client Lib
Database server
Database server
This driver converts JDBC calls into database-specific SQL statements. Though all DBMS use standard SQL for database interactions, all DBMS do not support all the features.
Amit Sharma
JDBC
DB Middleware
Database server Type 4
A Type 4 driver takes JDBC calls and translates them into the network protocol which is used directly by the DBMS. Thus direct calls can make to the DBMS server by the client machines or application server.
Amit Sharma
JDBC
Connection Management
Following classes / interfaces allow to establish a connection to the database Java.sql.DriverManager This class provides functionality to manage one or more database drivers. Each driver in turn lets you connect to a specific database. Java.sql.Driver This is an interface that abstracts the vendor specific connection protocol. Java.sql.connection This interface abstracts most of the interaction with the database. Using a connection, you can send SQL statements to the database, and read the results of execution.
Database Access
After obtaining a connection following classes / interfaces allow to send statements to the database Java.sql.Statement This inteface lets you to execute SQL statements over the underlying connection and access the result. Java.sql.PreparedStatement This is a variant of java.sql.Statement interface, which allows parameterized SQL statements. Parameterized SQL statements include parameter markers (as ?), which can be replaced with actual value later on.
Database Access
Java.sql.CallableStatement This interface lets you to execute stored procedure. java.sql.ResultSet This interface abstracts the result of SELECT statements. It also provides methods to access the results row by row.
Amit Sharma
JDBC
Amit Sharma
JDBC
1.Establish a connection
Remember, The loading of the database driver does not connect to the database; but it merely creates an environment in the program where this can be done. Prior to any database specific SQL statements can be executed, the requirement is, a connection must be established to the database. This can accomplished through a call to the DriverManager getConnection method to find a specific driver that can create a connection to the URL requested.
Amit Sharma
JDBC
1.Establish a connection
import java.sql.*; Load the vendor specific driver
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
Dynamically loads a driver class, for Oracle database
The first step in using JDBC is to load the JDBC-ODBC bridge driver. This is usually accomplished by the forName static method of the Class object which is the part of base Java system.
1.Establish a connection
Make the connection
Connection con =
DriverManager.getConnection("Jdbc:Odbc:emp");
The loading of JDBC driver does not connect to the database, but it creates the environment where it can be done. Here, the DriverManager searches through registered drivers until the required one is found whose URL is provided.
Amit Sharma JDBC Rapid Application Development-CS3011
Amit Sharma
JDBC
4. Get ResultSet
The SQL calls sends the queries to the database and returns the results of the query as a ResultSet. If there is an error to be generated during the execution of the query, an exception is generated and caught using the try catch block. Successful execution of the executeQuery moves control to the next line of code.
4. Get ResultSet
String queryStudent = "select * from Student"; ResultSet rs = Stmt.executeQuery(queryStudent);
Amit Sharma
JDBC
Iterate ResultSet
while (rs.next()) { int ssn = rs.getInt("SSN"); String name = rs.getString("NAME"); int marks = rs.getInt("MARKS"); }
Amit Sharma
JDBC
Close connection
stmt.close(); con.close();
Amit Sharma
JDBC
import java.sql.*; public class Display { public static void main(String[] args) { Connection conn; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); conn=DriverManager.getConnection("jdbc:odbc:sap","",""); Statement stmt = conn.createStatement(); ResultSet r = stmt.executeQuery ("SELECT * FROM emp"); while (r.next()){ System.out.println("Name : " + r.getString(1) + " " + r.getString(2)); System.out.println("Designation : " + r.getString(3)); System.out.println("Salary : " + r.getString(4) + "\n"); }
Amit Sharma JDBC Rapid Application Development-CS3011
Amit Sharma
JDBC
Creating Table
Following table is to be created
Employee_ID 6323 5768 Name Hemanth Bob
1234
5678
Shawn
Michaels
import javax.sql.*; public class Display { public static void main(String[] args) { Connection conn; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); conn=DriverManager.getConnection("jdbc:odbc:sap","",""); String createString stmt.executeUpdate("CREATE TABLE employee(Emp_code varchar(50),Emp_name varchar(50),Address varchar(50),Phone int,Designation varchar(50),Department varchar(50),Basic_salary int);"); Statement stmt = con.createStatement(); stmt.executeUpdate(createString); } stmt.close(); conn.close(); } catch (Exception e) { System.out.println("ERROR : " + e); e.printStackTrace(System.out); } }
Amit Sharma
JDBC
PreparedStatement updateSales = con.prepareStatement(update COFFEES set SALES = ? where COF_NAME like ?"); int [] salesForWeek = {175, 150, 60, 155, 90}; String [] coffees = {"Colombian", "French_Roast", "Espresso", "Colombian_Decaf", "French_Roast_Decaf"}; int len = coffees.length; for(int i = 0; i < len; i++) { updateSales.setInt(1, salesForWeek[i]); updateSales.setString(2, coffees[i]); updateSales.executeUpdate(); }
Amit Sharma JDBC Rapid Application Development-CS3011
try {
Amit Sharma
JDBC
Stored Procedures
A stored procedure is a group of SQL statements that form a logical unit and perform a particular task. Stored procedures are used to encapsulate a set of operations or queries to execute on a database server. For example, operations on an employee database (hire, fire, promote, lookup) could be coded as stored procedures executed by application code. Stored procedures can be compiled and executed with different parameters and results, and they may have any combination of input, output, and input/output parameters.
Stored Procedures
In some DBMSs, the following SQL statement creates a stored procedure: create procedure SHOW_SUPPLIERS as select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME from SUPPLIERS, COFFEES where SUPPLIERS.SUP_ID = COFFEES.SUP_ID order by SUP_NAME
Amit Sharma JDBC Rapid Application Development-CS3011
Stored Procedures
The following code puts the SQL statement into a string and assigns it to the variable createProcedure, which we will use later: String createProcedure = "create procedure SHOW_SUPPLIERS " + "as " + "select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME " + "from SUPPLIERS, COFFEES " + "where SUPPLIERS.SUP_ID = COFFEES.SUP_ID " + "order by SUP_NAME";
Amit Sharma
JDBC
CallableStatement cs SHOW_SUPPLIERS}");
con.prepareCall("{call
ResultSet rs = cs.executeQuery();
Amit Sharma JDBC Rapid Application Development-CS3011