0% found this document useful (0 votes)
19 views40 pages

13 JDBC 10092024 014625pm

lecture

Uploaded by

Mehran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views40 pages

13 JDBC 10092024 014625pm

lecture

Uploaded by

Mehran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Discovering Knowledge

CSC-210
Object-Oriented Programming

Lecturer
Sameena Javaid

https://sites.google.com/site/sameenajavaidcs

© Bahria University Department of Computer Science | Bahria University 1


Discovering Knowledge

JAVA DATABASE

© Bahria University Department of Computer Science | Bahria University 2


Discovering Knowledge

What is JDBC?
• JDBC is a Java library which allows Java
programs to execute SQL inside databases.

© Bahria University Department of Computer Science | Bahria University 3


Discovering Knowledge

Oracle DB
JDBC in Use
driver
for Oracle

Sybase DB
Java JDBC driver
program
for Sybase
Connectivity
Data processing : // many more
Utilities

non-MS driver
for Access
Access DB

jdbc-odbc odbc
bridge driver

© Bahria University Department of Computer Science | Bahria University 4


Discovering Knowledge

The JDBC-ODBC Bridge


• ODBC (Open Database Connectivity) is a
Microsoft API that allows C/C++ programs
to execute SQL inside databases

• ODBC is supported by many database


companies.

© Bahria University Department of Computer Science | Bahria University 5


Discovering Knowledge

The JDBC-ODBC Bridge


• The JDBC-ODBC bridge allowed Java code to use the
C/C++ interface of ODBC

• The JDBC-ODBC bridge used to come free with Java:


– discontinued in Java 8

• Instead we will use the free "UCanAccess" non-


Microsoft driver for Access databases.
– this is a type 4 driver for JDBC

© Bahria University Department of Computer Science | Bahria University 6


Discovering Knowledge

Four Types of JDBC Driver


1. JDBC-ODBC Bridge (type 1)
translate Java to the ODBC API used by many
Windows-based databases, e.g. MS-Access

2. Database Protocol Driver (type 4)


Independent from the OS/hardware because the
driver is in Java.

© Bahria University Department of Computer Science | Bahria University 7


Discovering Knowledge

Four Types of JDBC Driver


3. Native API Connection Driver (type 2)
connected by a OS native module, dependent on
the OS or hardware (e.g. DLLs on Windows)

4. Net Connection Driver (type 3)


use Java to access the database via networking
middleware (usually TCP/IP) required for
networked applications

© Bahria University Department of Computer Science | Bahria University 8


Discovering Knowledge

Using UCanAccess
• Download UCanAccess-3.0.0-bin.zip from:
– http://sourceforge.net/projects/ucanaccess/
– unzip in directory with my code and batch files

• Documentation at:
– http://ucanaccess.sourceforge.net/site.html

© Bahria University Department of Computer Science | Bahria University 9


Discovering Knowledge

Some UCanAccess Features


• Supports many old Access formats
• SELECT, INSERT, UPDATE, DELETE
• DDL: CREATE table with primary key, DROP
• Transactions and savepoints
• Concurrent access from multiple users
• ANSI 92 SQL, core SQL-2008, MS Access SQL
• LIKE operator, wildcard character

© Bahria University Department of Computer Science | Bahria University 10


Discovering Knowledge

JDBC as a Diagram
creates creates creates
DriveManager Connection Statement ResultSet

SQL data

make link Driver


to driver
SQL data

© Bahria University Department of Computer Science | Bahria University 11


Discovering Knowledge

DriveManager
• It is responsible for establishing the connection
to the database through the driver.
• e.g.
Class.forName(

"net.ucanaccess.jdbc.UcanaccessDriver");
Connection conn =
DriveManager.getConnection(url);
name of the database

© Bahria University Department of Computer Science | Bahria University 12


Discovering Knowledge

Name the Database


• The name and location of the database is
given as a URL
– the details of the URL vary depending on the type
of database that is being used

© Bahria University Department of Computer Science | Bahria University 13


Discovering Knowledge

UCanAccess Database URL

jdbc:ucanaccess:// host.domain.com: 2048 c:/file

The comms The machine The port The path to


protocol holding the used for the the database
database. connection. on the machine
(accdb or mdb)

e.g. jdbc:ucanaccess://Books.accdb

© Bahria University Department of Computer Science | Bahria University 14


Discovering Knowledge

Statement Object
• The Statement object provides a ‘workspace’
where SQL queries can be created, executed,
and results collected.
• e.g.
Statement st = conn.createStatement():
ResultSet rs = st.executeQuery(
“select * from Authors”);
:
st.close();

© Bahria University Department of Computer Science | Bahria University 15


Discovering Knowledge

ResultSet Object
• Stores the results of a SQL query.

• A ResultSet object is similar to a ‘table’


of answers, which can be examined by
moving a ‘pointer’ (cursor).

Continued
© Bahria University Department of Computer Science | Bahria University 16
Discovering Knowledge

Cursor
cursor
23 John
5 Mark
17 Paul
• Cursor operations: 98 Peter
– first(), last(), next(), previous(), etc.

• Typical code:
while( rs.next() ) {
// process the row;
}
© Bahria University Department of Computer Science | Bahria University 17
Discovering Knowledge

import java.sql.*; SimpleJDBC.java


import net.ucanaccess.jdbc.*;

public class SimpleJDBC {

public static void main(String[] args) {


try {
// load the UCanAccess driver
Class.forName( "net.ucanaccess.jdbc.UcanaccessDriver" );
// connect to the database using the DriverManager
String url =
"jdbc:ucanaccess://C:/Users/INTEL/Documents/NetBeansProjects/JDBC_Example
/database/Books.accdb";

Connection conn = DriverManager.getConnection(url);

Statement st = conn.createStatement();

ResultSet rs = st.executeQuery("SELECT lastName, firstName FROM


Authors" );

© Bahria University Department of Computer Science | Bahria University 18


Discovering Knowledge

SimpleJDBC.java
while( rs.next() )
System.out.println( rs.getString("lastName") + ", " +
rs.getString("firstName") );

st.close();
conn.close();
}
catch (ClassNotFoundException e) {
System.out.println("Could not load UCanAccess library: " +
e);
}
catch (SQLException e) {
System.out.println("SQL Exception: " + e);
}
} // end of main()

} // end of SimpleJDBC class

© Bahria University Department of Computer Science | Bahria University 19


Discovering Knowledge

Execution

© Bahria University Department of Computer Science | Bahria University 20


Discovering Knowledge

Accessing a ResultSet
• The ResultSet class contains many methods
for accessing the value of a column of the
current row
– can use the column name or position
– e.g. get the value in the lastName column:
rs.getString("lastName")
OR
rs.getString(2);

© Bahria University Department of Computer Science | Bahria University 21


Discovering Knowledge

Accessing a ResultSet
• There are many methods for accessing the
data, e.g.
– getString(), getDate(), getInt(),
getFloat(), getObject()

• JDBC documentation starts at:


– http://docs.oracle.com/javase/7/docs/api/
java/sql/package-summary.html
– look in "ResultSet"

© Bahria University Department of Computer Science | Bahria University 22


Discovering Knowledge

Using MS Access
• MS Access changed its file formats when
Access 2007 was released:
– for Access 2003 (and earlier) you should use
Books.mdb
– for Access 2007 and later, you should use
Books.accdb

© Bahria University Department of Computer Science | Bahria University 23


Discovering Knowledge

Access and SQL


• How to use SQL in Access is described at:
– http://www.jaffainc.com/SQLStatementsInAccess.htm

© Bahria University Department of Computer Science | Bahria University 24


Discovering Knowledge

TableRelationships in Books.accdb

Under Database Tools > Relationships

© Bahria University Department of Computer Science | Bahria University 25


Discovering Knowledge

More Information
• Java: How to Program, 10th edition
Paul Deitel and Harvey Deitel, Pearson, 2015,
Chapter 24

• The JDBC tutorial is very good


– http://docs.oracle.com/javase/tutorial/jdbc

© Bahria University Department of Computer Science | Bahria University 26


Discovering Knowledge

Case Study Database


Applications

© Bahria University Department of Computer Science | Bahria University 27


Discovering Knowledge

Personal Data
Application

© Bahria University Department of Computer Science | Bahria University 28


Discovering Knowledge

Personal Data Application


1. Start Microsoft Access 2007/2010/2013
2. Create a database name “PersonalInfo”
3. Create a table name “Person” with these fileds
1. id AutoNumber
2. name Text
3. address Text
4. phone Text

© Bahria University Department of Computer Science | Bahria University 29


Discovering Knowledge

Creating Database in MS-Access

© Bahria University Department of Computer Science | Bahria University 30


Discovering Knowledge

Creating Table & Inserting Values

© Bahria University Department of Computer Science | Bahria University 31


Discovering Knowledge

Connecting with
MS-ACCESS

© Bahria University Department of Computer Science | Bahria University 32


Discovering Knowledge

ucanaccess
• http://sourceforge.net/projects/ucanaccess/files/

© Bahria University Department of Computer Science | Bahria University 33


Discovering Knowledge

Extract Library Files

© Bahria University Department of Computer Science | Bahria University 34


Discovering Knowledge

Add Library files to Project

© Bahria University Department of Computer Science | Bahria University 35


Discovering Knowledge

Add connection url code


String url =
"jdbc:ucanaccess://C:/Users/INTEL/Document
s/NetBeansProjects/JDBCDemo/
personInfo.accdb";

Compile and execute.

© Bahria University Department of Computer Science | Bahria University 36


Discovering Knowledge

/*
Retrieving Data from ResultSet
* Reads the fields of Person Table from PersonalInfo database and print the
screen.
*/

// File JdbcExample.java
//step 1: import package
import java.sql.*;
public class JdbcExample {
public static void main (String args[ ]) {
try {
//Step 2: load driverClass.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
//Step 3: define the connection URL
String url = "jdbc:ucanaccess://C:/Users/INTEL/Documents/
NetBeansProjects/JDBCDemo/personInfo.accdb";
//Step 4: establish the connection
Connection con = DriverManager.getConnection(url);
//Step 5: create Statement
Statement st = con.createStatement();
//Step 6: preapare & execute the query
String sql = “SELECT * FROM Person”;
ResultSet rs = st.executeQuery(sql);

© Bahria University Department of Computer Science | Bahria University 37


Discovering Knowledge

Retrieving Data from ResultSet


//Step 7: process the results
while(rs.next()){
// The row name is “name” in database “PersonInfo,
// hence specified in the getString()method.
String name = rs.getString(“name”);
String add = rs.getString(“address”);
String pNum = rs.getString(“phone”);
System.out.println(name + “ ” + add + ” ” + pNum);
}
//Step 8: close the connection
con.close();
}catch(Exception sqlEx){
System.out.println(sqlEx);
}
} // end main
} // end class
© Bahria University Department of Computer Science | Bahria University 38
Discovering Knowledge

Output of Retrieving Data from ResultSet

© Bahria University Department of Computer Science | Bahria University 39


Discovering Knowledge

1.
References
Sharon Zakhour et al, The Java Tutorial Fourth Edition,
http://java.sun.com/docs/books/tutorial
2. Cay Horstmann, Big Java: Earl Objects 5th Edition, John Wiley & Sons,
2013
3. Deitel & Deitel, Java Howto Program 9th Edition, Prentice Hall, 2012
4. Richard M. Reese, Oracle Certified Associate Java SE 7 Programmer
Study Guide, Packt Publishing, 2012
5. Walter Savitch, Absolute Java 5th Edition, Pearson Education, 2013
6. Mark Allen Weiss, Data Structures and Algorithm Analysis in Java 3rd
Edition, Pearson Education, 2012
7. Anany Levitin, Introduction to the Design and Analysis of Algorithms 3rd
Edition, Pearson Education, 2012
8. Ying Bai, Practical Database Programming with Java, John Wiley & Sons,
2011
© Bahria University Department of Computer Science | Bahria University 40

You might also like