0% found this document useful (0 votes)
18 views25 pages

Slot 1B JDBC

Uploaded by

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

Slot 1B JDBC

Uploaded by

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

Lecture 05

JDBC Database Access


JDBC- Java Database Connectivity

References:
• Java-Tutorials/tutorial-2015/jdbc/index.html
• Java Documentation, the java.sql package
Why should you study this lecture?

— In almost all large applications. Data are


organized and stored in databases which are
managed by database management systems
(DBMS) such as MS Access, MS SQL Server,
Oracle, My SQL,…
— Do you want to create Java applications which
can connect to DBMSs?
— Database programming is a skill which can not be
missed for programmers.
Objectives

— Introduction to databases
— Relational Database Overview
— JDBC and JDBC Drivers
— Steps to develop a JDBC application.
— Test connection in Netbeans.
Contents

1- Database and DBMS


2- Relational Database Overview
3- JDBC and JDBC Drivers
4- Steps to develop a JDBC Application
5- A Demonstration
1- Database and DBMS
— Database is a collection of related data which are
stored in secondary mass storage and are used by
some processes concurrently.
— Databases are organized in some ways in order to
reduce redundancies.
— DBMS: Database management system is a software
which manages some databases. It supports ways to
users/processes for creating, updating, manipulating
on databases and security mechanisms are
supported also.
— DBMS libraries (C/C++ codes are usually used)
support APIs for user programs to manipulate
databases.
2- Relational Database Overview
— Common databases are designed and implemented
based on relational algebra (set theory).
— Relational database is one that presents information
in tables with rows and columns.
— A table is referred to as a relation in the sense that it
is a collection of objects of the same type (rows).
— A Relational Database Management System
(RDBMS)- such as MS Access, MS SQL Server,
Oracle- handles the way data is stored, maintained,
and retrieved.
RDBMS:
Structure Query Language (SQL)
Data Definition Language (DDL):
CREATE…/ ALTER…/ DROP… 3 languages:

Data Manipulating
Language (DML):
SELECT…/ INSERT INTO …
/ UPDATE … / DELETE

Data Control Language (DCL):


GRANT…/ REVOKE … / DENY…
RDBMS: SQL…

— Common DML queries:

— SELECT columns FROM tables WHERE condition


— UPDATE table SET column=value,… Where condition
— DELETE FROM table WHERE condition
— INSERT INTO table Values ( val1, val2,…)
— INSERT INTO table (col1, col2,…) Values ( val1, val2,…)
3-JDBC and JDBC Driver

— The JDBC™ API was designed to keep simple


things simple. This means that the JDBC makes
everyday database tasks easy. This trail walks
you through examples of using JDBC to execute
common SQL statements, and perform other
objectives common to database applications.
— The JDBC API is a Java API that can access any
kind of tabular data, especially data stored in a
Relational Database.
JDBC and JDBC Driver…
— JDBC APIs has 02 parts in the java.sql package.
Part Details Purposes

JDBC Driver DriverManager class Java.lang.Class.forName(DriverClass) will dynamically


load the concrete driver class, provided by a specific
provider for a specific database. This class
implemented methods declared in JDBC interfaces.
The class DriverManager will get a connection to database
based on the specific driver class loaded.
JDBC API Interfaces:
Connection, For creating a connection to a DBMS
Statement For executing SQL statements
ResultSet For storing result data set and achieving columns
DatabaseMetadata For getting database metadata
ResultSetMetadata For getting resultset metadata
Classes
SQLException
Refer to the java.sql package for more details in Java documentation
JDBC and JDBC Driver…
Java App.

Connection con Statement stmt ResultSet rs

DriverManager executeQuery()

createStatement()
getConnection()
Process rs
Specific JDBC Driver
implement interfaces
(loaded dynamically by
java.lang.Class)

Model of a JDBC App.


Database
Type 4-Driver: Native Protocol

Application
— Communicates directly with the
database using Java sockets Java Application
— Improves the performance as
translation is not required
— Converts JDBC queries into
native calls used by the particular Type IV JDBC
RDBMS Driver
— The driver library is required
when it is used and attached with SQL command Result Set
the deployed application
(sqlserver 2000: mssqlserver.jar,
msutil.jar, msbase.jar; sqlserver use Proprietary protocol
2005: sqljdbc.jar; jtds: jtds.jar …)
— Independent platform Database
Download Type 4 SQL Server JDBC
Google : Microsoft SQL Server JDBC Driver

MS SQL Server 2008


Setup
MS SQL Server 2005
Configure Ports, Protocols for SQL Server

Enable Server protocols and port

Right
click

Attention: Disable VIA

Enable client protocols and port


Configure Ports, Protocols for SQL Server…

Stop then restart SQL Server and SQL Server Agent for settings are affected.

Right
click
Test connection in Netbeans
Test connection in Netbeans
Test connection in Netbeans
Test connection in Netbeans
4-Steps to Develop a JDBC Application

Step Description Use ( java.sql package) Methods

1 Load JDBC Java.lang.Class forName(…)


Driver
2 Establish a DB java.sql.Connection
connection java.sql.DriverManager DriverManager getConnection(…)
à Connection
3 Create & java.sql.Statement execute(…)
execute SQL java.sql.PrepareStatement executeQuery(…) à SELECT
statements java.sql.CallableStatement executeUpdate(…) à
INSERT/UPDATE/DELETE
4 Process the java.sql.ResultSet first(), last(), next(), previous()
results getXXX(..)
5 Close ResultSet, Statement, close()
Connection
Step 1,2 : Make connection

21/40
Step 3: Create &Execute a SQL statement

String sql1 = “SELECT columns FROM table1, table2, … WHERE condition”;


String sql2 = “UPDATE table SET column = value, … WHERE condition”;
String sql3 = “INSERT INTO table VALUES ( val1, val2, … )” ;
String sql4 = “INSERT INTO table (col1, col2, col3) VALUES ( val1, val2, val3)” ;
String sql5 = “UPDATE table SET col1 = ?, col2=? WHERE condition”;

// Connection con was created


Statement stmt= con.createStatement();
ResultSet rs= stmt.executeQuery(sql1);
int numOfInfectedRows = stmt.executeUpdate(sql2);
int numOfInfectedRows = stmt.executeUpdate(sql3);
int numOfInfectedRows = stmt.executeUpdate(sql4);

PreparedStatement pStmt = con.preparedStatement(sql5);


pStmt.setXXX (index, val); // from 1
int numOfInfectedRows = pStmt.executeUpdate(); // no argument
Step 4: Process the results

BOF Move the current row:


boolean next(), previous(), first(), last()
Record 1
Default: Result set moves forward only.
Record 2

Record 3 Get data in columns of the current row:


TYPE getTYPE ( int columnIndex) // begin from 1
…..
TYPE getTYPE ( String columnLabel)
…..

….. SELECT desc AS description FROM T_employee


èColumn name: desc
EOF
èColumn Label: description
ResultSet

At a time, resultset maintains a current position. When the resultset is initialized, the
position is the BOF position. An exception is thrown when the current position is
out of its scope.
Step 5: Close the connection
Opening Order: Connection Statement ResultSet

Closing Order: ResultSet Statement Connection

Attention!!!
At a time, a connection can be bound with ONLY ONE result set.
An exception will be thrown if we try binding a connection with another result set.
EX:
String sql1 =“SELECT…”;
String sql2 =“SELECT…”;
ResultSet rs1= stmt.executeQuery(sql1);
ResultSet rs2= stmt.executeQuery(sql2); è EXCEPTION
èYou should close the rs1 before trying get the rs2 result set
èSolution: Transfer data in the rs1 to ArrayList (or Vector) then close rs1 before get new
data to rs2.
Thank You

You might also like