Online Software Educational Training - IT Tutorials - Online Education Training for Computer Software


Home

JAVA JDBC

The JDBC Trail

 

Objectives

  • What is JDBC? 
  • How to access a Database using JAVA? 
  • JDBC Syntax. 
  • Different types of JDBC configuration in use.

  

What Is JDBC?

 

Duel with the database

  • Connect to any database
  • Execute SQL
  • Process the results
  • Spend your time on database issues -- not JDBC issues

JDBC versus ODBC and other API

  • ODBC is hard to learn. It mixes simple and advanced features together, and it has complex options even for simple queries.
  • JDBC, on the other hand, was designed to keep simple things simple while allowing more advanced capabilities where required.
  • ODBC driver manager and drivers must be manually installed on every client machine.
  • JDBC code is automatically installable, portable, and secure on all Java platforms from network computers to mainframes.
  • JAVA can use ODBC, but this is best done with the help of JDBC in the form of the JDBC-ODBC Bridge,

 

JDBC ENVIRONMENT

 

STEPS INVOLVED in JDBC

 

  1. Install JDBC package or JDBC-ODBC package and necessary database driver.
  2. Open the database connection.
  3. Create a SQL statement or procedures call.
  4. Execute the SQL statement or procedure call.
  5. Process the results.
  6. Commit or rollback the transaction.
  7. Close the results.
  8. Close the statement.
  9. Close the Database Connection.

 STEP 1:-

 Configuring the JDBC

 Case 1: JDK 1.1.1 and above , no need. (JDBC, JDBC-ODBC Package are included with the JDK kit).

 Case 2: JDK 1.02, Get the driver from JavaSoft JDBC.

 Configuring the JDBC-ODBC Bridge

 Install JDBC-ODBC Bridge

 Install ODBC Driver

 Configure ODBC

 STEP 2:- Connecting to Database.

 Invoke the JDBC Package

import java.sql.*;

Load the Application Driver

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

 

Create a database URL

String url="jdbc:odbc:dsn";

Assign the user ID and password

String user="guest";

String pwd="guest";

Open a Connection

Connection con=DriverManager.getConnection(url,user,pwd)

(Throw SQLException)

Other Settings

con.AutoCommit(true);

Transaction are automatically committed when executed.

con.setReadOnly(true);

 

Step 3: Create a SQL statement.

  • Create a statement object

Statement stmt = con.createStatement();

(Throws SQLException)

  • Set the Query String

String query="Select * from table_name";

Step 4: Execute the SQL Statement

ResultSet rs=stmt.executeQuery(query);

(Throws SQLException)

 Step 5: Process the results of SQL statement.

     

  • Read the Next Row

boolean found=rs.next();

  • Extract the Column Values

rs.getInt(column number or field name);

rs.getString(column number or field name);

rs.getDate(column number or field name);

rs.getTime(column number or field name);

 

Step 6: Commit or rollback the transaction

  con.commit();

con.rollback();

 

Step 7: Close the resultset.

  rs.close();

 

Step 8: Close statement.

stmt.close();

 

Step 9: Close the connection.

con.close();

 

JDBC: Calling a Stored Procedures

  • These calls are performed using the CallableStatement interface, which is an extension of the PreparedStatement interface. 
  • Parameters passed to and from the stored procedure are identified using placeholder symbols.  
  • These placeholders must be registered as IN our OUT data elements, using data types from the Types class 

 

Steps for calling the Procedures or function Call

 Create the Command with Placeholders:

 // Stored procedure call

String command = "{call PROCEDURENAME(?,?,?,?)}";

// 4 placeholders

 // Stored function call

String command = "{? = call FUNCTIONNAME(?, ?, ? , ?)}";

// 4 placeholders + 1 return value

 

Create a Callable Statement Object

 CallableStatement cstmt = con.prepareCall (command);

(Throws a SQLException error.)

 Register the IN and OUT Placeholders

 // Assign IN parameters (use positional placement)

cstmt.setInt(1, 50);

// first placeholder has an integer value of 50

cstmt.setString(2, "Smith");

// second placeholder has a string value of "Smith"

cstmt.registerOutParameter(3, Types.NUMERIC);

//NUMERIC is preferred over INTEGER with some databases

cstmt.registerOutParameter(4, Types.VARCHAR);

// fourth placeholder is an OUT field of type VARCHAR.

(Throws a SQLException error.)

 

Execute the Procedure or Function Call

cstmt.execute();

(Throws a SQLException error.)

 

Process the OUT Placeholders

BigDecimal num = cstmt.getBigDecimal(3,0);

String str = cstmt.getString(4);

(Throws a SQLException error.)

 

Close the CallableStatement Object

// Close the call object after update is complete

cstmt.close();

(Throws a SQLException error.)

 

Accessing Metadata

 

What is metadata?

 It is descriptive information about database structure and connections.

e.g.

    • Who is connected to the Database?
    • Is the database read only? 
    • Valid data types for the database 
    • Data type of the column. 
    • How does the database vendor deals with the stored procedure? 
    • How does the database handle cursor across rollback and commit?   
    • How many columns were retrieved in each row of the result? 
    • What's is the SQL type, column name? 
    • What is the Table name? 
    • How many decimal digits does a column have? 

 Syntax :

  DatabaseMetaData dmeta=con.getMetaData();

ResultsetMetaData rsmeta=rs.getMetaData();

 

CLIENT-SERVER DESIGN CONSIDERATION

 

Two-Tier Model

    • Client makes direct calls to the database.  
    • Java applets performing the JDBC calls.

 

 Advantages 

    • Maintains a persistent connection with the database.  
    • Minimizes resource requirements on the Web server by processing locally on the client.  
    • Results in performance gains over the network because of the direct interaction with the database.  

Disadvantages 

  • The JDBC drivers may not be supported by some commercial browsers. 
  • These driver types typically call a native database driver, such as ODBC or another vendor-provided load module (e.g. DLL). These calls may be considered a security violation by the browser, since they create a potential risk for computer viruses. (Browsers with built-in support of JDK 1.1 are not restricted in this way.)  
  • Because the applet calls the database directly, the native database drivers must be installed and maintained on each client computer that will be running the applet. This increases the administrative requirements for all clients that require access to the database. 

 

Three Tier Model using CGI 

  • The three-tier model introduces a middle layer that performs the interaction with the database.  
  • The middle layer is CGI (Common gateway interface). 

Advantages 

    • Presents no security risk to the client and is supported by commercial browsers.  
    • No maintenance is required on the clients, because all database access is performed on the Web server.  
    • Provides central control and administration of database logic on the Web server.  

 Disadvantages 

    • Some performance loss is expected because of the middle layer (CGI).  
    • Unable to maintain a persistent connection to the database.  
    • Increases resource requirements on Web server.

 

Summary  

  • JDBC is ready for work  
  • Java with JDBC is a sophisticated database development tool  
  • JDBC connectivity is good today and getting better  
  • Either using JDBC directly or via Java application builders.

 

Sample Code : (Using JDBC-ODBC Bridge)

 import java.sql.*;

class Sample {

static Connection con; // database connection object

/** Main routine */

Public static void main(String args[]) throws Exception {

// Load the JDBC-ODBC bridge driver

Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");

 // Open the database and display all rows in a table

open();

insert();

select();

 // Add a new row and show the result

insert();

//select("WHERE EmpCode = 11");

 // Update a row and commit the result

update(true);

select("WHERE EmpCode = 11");

 // Update a row and rollback the result

update(false);

select("WHERE EmpCode = 100");

 // Delete a row and show the result

delete();

select("WHERE EmpCode = 100");

 // Close the database

close();

 }

 /** Open a database connection */

static void open() throws SQLException {

 // ODBC data source name where db4 is the database name

// It is a MsAccess database file.

String dsn = "jdbc:odbc:db4";

String user = "guest";

String password = "";

 // Connect to the database

con = DriverManager.getConnection(dsn, user, password);

 // Shut off autocommit

con.setAutoCommit(false);

 }

 /** Commit all pending transactions and close the database connection */

static void close() throws SQLException {

 con.commit();

con.close();

 }

 /** Issue a SQL query with a WHERE clause */

 static void select(String whereClause) throws SQLException {

 Statement stmt; // SQL statement object

String query; // SQL select string

ResultSet rs; // SQL query results

boolean more; // "more rows found" switch

 query = "SELECT Empcode, name "

+ "FROM table1 ";

 stmt = con.createStatement();

rs = stmt.executeQuery(query);

 // Check to see if any rows were read

more = rs.next();

if (!more) {

 System.out.println("No rows found.");

return;

 }

 // Loop through the rows retrieved from the query

while (more) {

 System.out.println("ID: " + rs.getInt("EmpCode"));

System.out.println("Name: " + rs.getString("Name"));

System.out.println("");

more = rs.next();

 }

 rs.close();

stmt.close();

 }

 /** Issue a SQL query without a WHERE clause */

static void select() throws SQLException {

 select("");

 }

 /** Insert a new row */

static void insert() throws SQLException {

 Statement stmt; // SQL statement object

String sql; // SQL insert command

int rows; // Number of rows inserted

 sql = "INSERT INTO Table1 "

+ "VALUES (11, 'Gaurav')";

 stmt = con.createStatement();

rows = stmt.executeUpdate(sql);

con.commit();

stmt.close();

 System.out.println(rows + " row(s) added");

 }

 /** Update a new row */

static void update(boolean commit) throws SQLException {

 Statement stmt; // SQL statement object

String sql; // SQL update command

int rows; // Number of rows inserted

String title; // New title for the update

 if (commit)

title = "Arun";

else

title = "Aniesh";

 sql = "UPDATE Table1 "

+ "SET Name='" + title + "' "

+ "WHERE EmpCode = 2";

 stmt = con.createStatement();

rows = stmt.executeUpdate(sql);

 if (commit)

con.commit();

else

con.rollback();

 stmt.close();

System.out.println(rows + " row(s) updated");

 }

 /** Delete a row */

static void delete() throws SQLException {

 Statement stmt; // SQL statement object

String sql; // SQL delete command

int rows; // Number of rows inserted

 sql = "DELETE FROM Table1 "

+ "WHERE EmpCode = 11";

 stmt = con.createStatement();

rows = stmt.executeUpdate(sql);

con.commit();

stmt.close();

 System.out.println(rows + " row(s) deleted");

 }

 }

 


Previous

Next