0% found this document useful (0 votes)
95 views26 pages

Tutorial: Advanced Java Programming and Database Connection

The document provides an overview of exception handling and database connectivity using JDBC in Java. It discusses the try, catch, and finally blocks for exception handling and separating error handling code. It also covers the different types of JDBC drivers and how to load a driver, create a connection, statement, and retrieve results using ResultSet to access and query a database. The document uses examples to demonstrate creating a database, table, and user account in MySQL.

Uploaded by

arunkpanda
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
95 views26 pages

Tutorial: Advanced Java Programming and Database Connection

The document provides an overview of exception handling and database connectivity using JDBC in Java. It discusses the try, catch, and finally blocks for exception handling and separating error handling code. It also covers the different types of JDBC drivers and how to load a driver, create a connection, statement, and retrieve results using ResultSet to access and query a database. The document uses examples to demonstrate creating a database, table, and user account in MySQL.

Uploaded by

arunkpanda
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 26

Tutorial:

Advanced Java Programming


and Database connection
Agenda

• Exceptions and Error Handling


– What is it and why do we need it?
– The try, catch, finally procedure
• Database Access with JDBC
– Installations
– Connecting and querying the database
– Complete example
• References

Advanced Java Programming – Eran Toch 2


Methodologies in Information System Development
Exceptions - Introduction

• Definition:  An exception is an event that


occurs during the execution of a program that
disrupts the normal flow of instructions.
• What’s wrong with using the return value for
error handling?
– Advantage 1: Separating Error Handling Code from
"Regular" Code
– Advantage 2: Propagating Errors Up the Call Stack
– Advantage 3: Grouping Error Types and Error
Differentiation

Advanced Java Programming – Eran Toch 3


Methodologies in Information System Development
Exceptions – Advantage 1
Separating Error Handling Code from "Regular" Code:
errorCodeType readFile { readFile {
initialize errorCode = 0; try {
open the file; open the file;
if (theFileIsOpen) { determine its size;
determine the length of the allocate that much memory;
file; read the file into memory;
if (gotTheFileLength) { close the file;
allocate that much memory; } catch (fileOpenFailed) {
if (gotEnoughMemory) { doSomething;
read the file into } catch (sizeDeterminationFailed) {
memory; doSomething;
if (readFailed) { } catch (memoryAllocationFailed) {
errorCode = -1; doSomething;
} } catch (readFailed) {
} else { doSomething;
errorCode = -2; } catch (fileCloseFailed) {
} doSomething;
. . . }
}

Without Exception With Exception


4
The try Block

• try block:
try {
System.out.println("Entering try statement");
out = new PrintWriter(new FileWriter("OutFile.txt"));
}
for (int i = 0; i < size; i++)
out.println("Value at: " + i + " = " + victor.elementAt(i));

• A try statement must be accompanied by at


least one catch block or one finally block.

5
The catch Block

• catch block handles the exception:


try {
. . .
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Caught
ArrayIndexOutOfBoundsException: " +
e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: "
+ e.getMessage());
}

• Multiple catch blocks can be placed, each


handling a different type of exception

6
Catching Multiple Exceptions

• Java exceptions are Throwable objects


Throwable

Exception

MyException

MySpecificException2 MySpecificException1

• Catching MyException will catch both the


subclasses. Catching Exception will catch all
types of Exceptions
Advanced Java Programming – Eran Toch 7
Methodologies in Information System Development
Catching Multiple Exceptions – cont’d

• Example: The following catch block, will


catch all types of exceptions:

} catch (Exception e) {
System.err.println("Exception caught: " + e.getMessage());
}

8
The finally Block

• We can never be sure that either the try block


or the finally block will be fully executed.
• finally block code will always be executed:
finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}

• Used frequently for cleanup processes.

9
Putting it All Together
public void writeList() {
PrintWriter out = null;

try {
System.out.println("Entering try statement");
out = new PrintWriter(
new FileWriter("OutFile.txt"));
for (int i = 0; i < size; i++)
out.println("Value at: " + i + " = " + victor.elementAt(i));
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Caught ArrayIndexOutOfBoundsException: " +
e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
}

10
throw Statement
• All Java methods use the throw statement to
throw an exception
• The method must declare that it might throw
something, by using the throws statement
public Object pop() throws EmptyStackException {
Object obj;

if (size == 0)
throw new EmptyStackException(“exception text”);

obj = objectAt(size - 1);


setObjectAt(size - 1, null);
size--;
return obj;
}

11
Exceptions and JavaDoc

• Exception can be documented by Javadoc


using the @exception statement

/**
* regular javadoc text…
* @throwsExceptionIf the Driver was not found.
* @throwsSQLExceptionIf the the <code>DriverManager.getConnection
* </code> method returned an error.
*/
public void createConnection()throws SQLException, Exception{

12
Agenda

• Exceptions and Error Handling


– What is it and why do we need it?
– The try, catch, finally procedure
• Database Access with JDBC
– Installations
– Connecting and querying the database
– Complete example
• References

13
JDBC

• Types

• Type1: JDBC-ODBC Bridge driver


• Type2: Native-API/ Partially java driver.
• Type3: All java/Net -Protocol driver.
• Type4: All java/Native-Protocol driver (pure).

14
Type 1

• The type1 driver translates all jdbc calls into odbc calls
and sends them to the odbc driver.

15
Advantage/Disadvantage

Type1 allows access to almost any database, since


odbc drivers are available.

It is not written fully in java so not portable.


Not good for web.
Odbc driver must be required to install.

16
Type 2

• The type2 driver translates all jdbc calls into database


specific calls.

17
Advantage/Disadvantage

Type2 offer better performance than the type1. and it


uses Native API which is database specific.

It is must be installed at client system and it is not used


in internet.
It is not written in java.

18
Type 3

• The type3 driver passed request through network to the


middle tier server. The middle layer then translates the
request into database

19
Advantage/Disadvantage

Type 3 is written in java so it portable for net.

It is so small so loaded very fast.

It requires another server application to install and


maintain.

20
Type 4

• Uses java networking libraries to communicate directly


with the data base server.

21
Advantage/Disadvantage

Type 4 is written completely in java so it portable for


net.

It is so small so loaded very fast.

With type 4 drivers, the user needs a different driver for


each database.

22
Accessing Database

1. Load the driver


2. Creating a connection object
3. Create a statement object
4. Execute an SQL query and get results using the
ResultSet object

23
Example – Database Management
mysql> create database mytest; Creating the DB
Query OK, 1 row affected (0.05 sec)
mysql> grant all on *.* to eran@localhost identified by '1234';
Query OK, 0 rows affected (0.14 sec) Creating user account
mysql>create table phones (name varchar(255) not null unique key, phone
varchar(25) not null);
Creating the ‘phones’
mysql>describe phones;
table
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+ Is everything alright?
| name | varchar(255) | | PRI | | | Let’s see…
| phone | varchar(25) | | | | |
+-------+--------------+------+-----+---------+-------+
mysql> insert into phones values ('Eran Toch', '+972-4-9831894');
Query OK, 1 row affected (0.11 sec)
Inserting some data

24
Example – Connection
import java.sql.*;
Importing java.sql.* that
public class SQLConnect { contains all the classes we
Connection conn = null; need
Statement stmt = null;
ResultSet rs = null; Connection, Statement and
public SQLConnect(){}
ResultSet are defined as
public void createConnection(){ class variables
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch (Exception E){ Dynamically loading the specific
System.out.println(E); JDBC driver. The runtime environment
} must know where the library is located!
try{

conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test” , user
,password);
}
catch (SQLException E){
Connecting to the database using
System.out.println(E); the url
}
}
25
Example – Access and Query
Creating a statement
public String getPhones(){
String output = ""; Creating a ResultSet, based
try {
on a SQL statement
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM phones");
if (rs != null){
while (rs.next()){ Going through the
output += rs.getString("phone") + "\n"; ResultSet by using
} rs.next(). Remember – you
} need to call the next method
} before you start reading from the
catch (Exception E){ ResultSet
System.out.println(E.getMessage());
}

Reading a field from the


ResultSet

26

You might also like