Professional Documents
Culture Documents
Sapna Saxena
Lecturer, CSE Department Chitkara University
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.
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, there are set of class files which can be used to perform above tasks.
creates connection to the database java.sql.Driver: represents driver java.sql.Connection: represents a connection to the database java.sql.Statement: executes statements java.sql.Resultset: holds results of executing statements
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.
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.
JDBC Architecture
ResultSet
Statement
ResultSet
PreparedStatement
ResultSet
CallableStatement
Connection
ODBC Driver Driver Manager
JDBC ODBC Bridge ODBC Driver
Oracle Database Sybase Database
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 }
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.
Database server
Type 2
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.
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.
Data Types
With regard to Data types, the java.sql package also provides several java data types that correspond to some of the SQL types. These can be used to as appropriate depending on what a field in a result row corresponds to in the concerned database Java.sql.array Java.sql.Timestamp Java.sql.Blob java.sql.Ref Java.sql.Clob java.sql.Struct Java.sql.Date java.sql.Types Java.sql.Time
Database Metadata
The JDBC API also includes facilities to obtain metadata about the database, parameters to statements, and results java.sql.DatabaseMetadata used to obtain database features Java.sql.ResultsetMetadata provides methods to access metadata of resultset, such as the names of columns, their types, etc. Java.sql.ParameterMetadata allows you to access the database type of parameters in prepared statements.
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.
1.Establish a connection
import java.sql.*; Load the vendor specific driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
The first step in using JDBC is to load the JDBCODBC 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:sap","","");
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.
statement must be executed. This requires that a Statement object needs to be created to manage the SQL statements. This is accomplished with a call to the Connection class createStatement method.
"(123456789,abc,100)";
stmt.executeUpdate(insertStudent);
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);
Iterate ResultSet
while (rs.next()) { int ssn = rs.getInt("SSN"); String name = rs.getString("NAME"); int marks = rs.getInt("MARKS"); }
Close connection
stmt.close();
con.close();
import java.sql.*; import javax.sql.*; import java.lang.Object; import javax.swing.*; import javax.swing.table.*; import java.awt.*; 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"); }
Creating Table
Following table is to be created
Employee_ID 6323 5768 1234 Name Hemanth Bob Shawn
5678
Michaels
import java.sql.*; 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 = "create table Employees (" + "Employee_ID INTEGER, " + "Name VARCHAR(30))"; Statement stmt = con.createStatement(); stmt.executeUpdate(createString); } stmt.close(); conn.close(); } catch (Exception e) { System.out.println("ERROR : " + e); e.printStackTrace(System.out); } } }
that it is given an SQL statement when it is created. The advantage to this is that in most cases, this SQL statement is sent to the DBMS right away, where it is compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement SQL statement without having to compile it first.
for SQL statements with no parameters, you probably use them most often for SQL statements that take parameters. The advantage of using SQL statements that take parameters is that you can use the same statement and supply it with different values each time you execute it.
statement, "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?", which has also, in most cases, been sent to the DBMS and been precompiled.
question mark placeholders (if there are any) before you can execute a PreparedStatement object. You do this by calling one of the setXXX methods defined in the PreparedStatement class. If the value you want to substitute for a question mark is a Java int, you call the method setInt. If the value you want to substitute for a question mark is a Java String, you call the method setString, and so on. In general, there is a setXXX method for each primitive type declared in the Java programming language.
mark placeholder to a Java int with a value of 75: updateSales.setInt(1, 75); setXXX The first argument given to a setXXX method indicates which question mark placeholder is to be set, and the second argument indicates the value to which it is to be set. The next example sets the second placeholder parameter to the string " Colombian": updateSales.setString(2, "Colombian");
accomplish the updation: PreparedStatement updateSales = con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ? "); updateSales.setInt(1, 75); updateSales.setString(2, "Colombian"); updateSales.executeUpdate():
you would choose to use a PreparedStatement object with parameters instead of just a simple statement, since the simple statement involves fewer steps. If you were going to update the SALES column only once or twice, then there would be no need to use an SQL statement with input parameters. If you will be updating often, on the other hand, it might be much easier to use a PreparedStatement object, especially in situations where you can use a for loop or while loop to set a parameter to a succession of values.
PreparedStatement updateSales; String updateString = "update COFFEES " + "set SALES = ? where COF_NAME like ?"; updateSales = con.prepareStatement(updateString); 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(); }