You are on page 1of 27

Welcome to

JDBC Programming I

IBM
Unit Objectives

After completing this unit, you should be able to:


Code connection-related statements within a JDBC
application
Code the necessary import statements for JDBC interfaces
Embed INSERT, UPDATE, DELETE and simple SELECT
statements in JDBC applications
Write code to check for Warning and Exception
conditions and understand the SQLCA
Utilize parameter markers in JDBC application programs
Process data that allows NULL values
Understand database access security when using JDBC
What Is JDBC?

Java API for executing SQL


A set of classes and interfaces written in Java

A vendor-neutral dynamic SQL interface


Uses only dynamic SQL
JDBC Programming

1. Import appropriate Java packages and classes

2. Load appropriate JDBC driver

3. Connect to the database, specifying the location with a


URL and using the db2 subprotocol

4. Pass SQL statements to the database

5. Receive results

6. Close the connection


Import Classes and Load Driver

import java.sql.*; 1
import java.io.*;
import java.lang.*;

class MyJDBC {
static {

2 try { Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");
} catch (Exception e) {
e.printStackTrace();
}
Connect to Database

public static void main (String argv[]){


try {
1 Connection con = null;
2 String url = "jdbc:db2:sample";
if (argv.length == 0)

3 { con = DriverManager.getConnection(url); }
else if (argv.length == 2)
{ String userid = argv[0];
String passwd = argv[1];

4 con = DriverManager.getConnection(url,userid,passwd);
}
else
{ throw new Exception
("\n Usage: java MyJDBC[,username,password]\n");}
SELECT Statement

1 Statement stmt = con.createStatement();


2 ResultSet rs = stmt.executeQuery
("SELECT EMPNO, LASTNAME " +
" FROM TEMPL " +
" WHERE SALARY > 40000 " );

3 while ( rs.next() ) {
4 System.out.println("empno = " + rs.getString(1) +
"lastname = " + rs.getString(2) );
}
rs.close();
5
stmt.close();
6
con.close();
7
} catch (Exception e) {
e.printStackTrace();
8
}
UPDATE Statement

1 Statement updStmt = con.createStatement();


2 int numRows = updStmt.executeUpdate
("UPDATE TEMPL " +
" SET LASTNAME = 'Stohl' " +
" WHERE EMPNO = '000110' ");
System.out.println("Number of rows updated " + numRows);
Using Parameter Markers - UPDATE

1 PreparedStatement pUpd = con.prepareStatement


("UPDATE TEMPL " +
" SET SALARY = ? " +
" WHERE EMPNO = ? ");
2 pUpd.setString(1,argv[1]);
3 pUpd.setString(2,argv[2]);
4 int numRows = pUpd.executeUpdate();
System.out.println("Number of rows updated " + numRows);
5 pUpd.close();
Insert Statement

1 String sql = null;


sql = "INSERT INTO TEMPL (EMPNO, LASTNAME, SALARY)"
2 + "VALUES ('000110', 'Roth', 50000)",
3 stmt = con.createStatement();
4 insertCount = stmt.executeUpdate( sql );
Delete Statement

1 PreparedStatement pstmt = null;


2 String eno = "000110";
3 String mysql = null;
4 mysql = "DELETE FROM TEMPL WHERE EMPNO = ?";
5 pstmt = con.prepareStatement (mysql);
6 pstmt.setString (1, eno);
7 deleteCount = pstmt.executeUpdate();2
Declaring Host
Variables Language Definitions

GRAPHIC CHAR
FLOAT

Java
DB2
FORTRAN REFERENCE
LIBRARY

VARCHAR

DECIMAL COBOL

INTEGER
Declaring Host Variables - Java Program

Host variables follow normal Java variable syntax

Host variable names are treated by DB2 as global


to the source module in which they are defined
Declaration Considerations for Java
CREATE TABLE SIMPLE
(TITLE CHAR (20) NOT NULL,
NUMBER SMALLINT NOT NULL )

private static String title;


private static short number;
PreparedStatement pstmt;

sql = "SELECT TITLE FROM SIMPLE "


+ "WHERE NUMBER = ?";
pstmt = con.prepareStatement(sql);
pstmt.setInt (1, number);
ResultSet prs = pstmt.executeQuery();
While (prs.next())
{ title = prs.getString(1);}
DCLGEN

Generate table declaration -


db2dclgn (DCLGEN)
Creates Structures for host variables

Languages supported
C, Java, COBOL, FORTRAN

db2dclgn -D sample -T employee -L Java


Processing Null Values

In all but Java, use Indicator variables

In Java, compare the value of the host variable


with Java null

Java example:

sql = "SELECT MGRNO FROM EMP";


........
String mgrno = rs.getString(1);
if (mgrno == null)
{ System.out.println ("\n MGRNO is null \n");}
Example of Using the wasNull() Method
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery
("SELECT EMPNO, LASTNAME, EDLEVEL " +
" FROM EMP " );
while ( rs.next() ) {
String eno = rs.getString(1);
String lname = rs.getString(2);
short edlvl = rs.getShort(3);
if ( rs.wasNull() )
{ System.out.println ("\n Edlevel is null for EMPNO \n");
System.out.println (eno);
} // end if
else
{ System.out.println ("\n Edlevel is: \n");
System.out.println ( edlvl );

System.out.println ("\n For EMPNO = \n");


System.out.println (eno);
} // end else
Passing NULL Value - Java Program

Statement stmt = null;


sql = "UPDATE TEMPL SET PHONENO = ? "
+ "WHERE EMPNO = '000110' ";
stmt = con.prepareStatement(sql);
if (some condition)
{ stmt.setString (1, null); }
else
{ stmt.setString (1, newphone); }
updateCount = stmt.executeUpdate();
Example of Using the setNull() Method

PreparedStatement pstmt = null;


sql = "UPDATE EMP SET EDLEVEL = ? "
+ " WHERE EMPNO = '0000110' ";
pstmt = con.prepareStatement( sql );
if ( some condition )
{ pstmt.setNull (1, java.sql.Type.SMALLINT); }
else
{ pstmt.setShort( 1, 16 ); }
updateCount = pstmt.executeUpdate();
Determining Success of SQL Statements

DB2 provides information to the program on the success


or failure of the SQL statement

Java programs throw an SQLException

Other host languages check the SQLCA

SQLCODE and SQLSTATE can be checked to


determine precise error
SQLCA - SQL Communication Area

S
Q Information / SQLCODE
Program L
C
A

Executable SQL
DB2
SQLCA Codes

INTEGER CHAR(1)
CONDITION SQLCODE SQLWARNO REQUEST STATUS

<0
ERROR FAILED

>0 & SATISFIED WITH


OR 'W'
WARNING <> 100 SPECIAL CONDITION

(MORE)
+100 DATA NOT FOUND
NOTFOUND
SQLSTATE = "02000"

SUCCESS 0 AND ' '


SUCCESS
SQLCODE and SQLSTATE

SQLCODE detailed
possibly platform dependent
numeric

SQLSTATE first two characters - general


all five characters - more information
not as detailed as SQLCODE,
but not as platform dependent
SQLCA SQLERRD Third Element

PROGRAM:

SQLCA NUMBER
SQLCODE OF ROWS
SQLWARN0 AFFECTED
SQLERRD[2] DB2

INSERT T
E S
U
E Q
UPDATE R

DELETE
Error Processing

try {
sql = "DELETE FROM TEMPL WHERE EMPNO = 999";
psstmt = con.prepareStatement(sql);
1 deleteCount = psstmt.executeUpdate();
2 if (( SQLWarn = psstmt.getWarnings()) !=null)
{
System.out.println ("\n Warning received on a DELETE \n");}
} // end try
3 catch (SQLException x)
4 { if (x.getSQLState().equals("42818"))
{ System.out.println ("\n Operand data types not compatible \n");
} // end if
else { System.out.println ("\n Error deleting from TEMPL \n");
System.out.println ("\n Value of SQLCODE is: \n");
5 SQLCode = x.getErrorCode();
System.out.println (SQLCode);
} // end else
} // end catch
JDBC and Security

JDBC

DELETE FROM
TEMPL WHERE
ID = '123'

GRANT DELETE ON TABLE


USERA TEMPL TO USER USERA
Unit Summary
Since completing this unit, you should be able to:

Code connection-related statements within a JDBC


application

Code the necessary import statements for JDBC interfaces


Embed INSERT, UPDATE, DELETE and simple SELECT
statements in JDBC applications
Write code to check for Warning and Exception
conditions and understand th SQLCA

Utilize parameter markers in JDBC application programs


Process data that allows NULL values

Understand database access security when using JDBC

You might also like