SlideShare a Scribd company logo
1 of 57
Download to read offline
JDBC
Prepared by Viska Mutiawani
1 viska@unsyiah.ac.id
Subtopik JDBC
 Pengenalan JDBC
 JDBC driver
 Package java.sql
 Cara menggunakan JDBC
 Advance
2 viska@unsyiah.ac.id
Pengenalan JDBC
3 viska@unsyiah.ac.id
JDBC – Java Database Connectivity
 JDBC is a standard interface for connecting to
relational databases from Java.
 The JDBC classes and interfaces are in the java.sql
package.
 JDBC 1.22 is part of JDK 1.1; JDBC 2.0 is part of
Java 2
4 viska@unsyiah.ac.id
Apakah itu JDBC?
 JDBC provides Java applications with access to
most database systems via SQL
 The architecture and API closely resemble
Microsoft's ODBC
 JDBC 1.0 was originally introduced into Java 1.1
 JDBC 2.0 was added to Java 1.2
 JDBC is based on SQL-92
 JDBC classes are contained within the java.sql
package
 There are few classes
 There are several interfaces
5 viska@unsyiah.ac.id
Database connectivity history
 Before APIs like JDBC and ODBC, database
connectivity was tedious
 Each database vendor provided a function library for
accessing their database
 The connectivity library was proprietary.
 If the database vendor changed for the application, the
data access portions had to be rewritten
 If the application was poorly structured, rewriting its data
access might involve rewriting the majority of the
application
 The costs incurred generally meant that application
developers were stuck with a particular database product
for a given application
6 viska@unsyiah.ac.id
Arsitektur JDBC
With JDBC, the application programmer uses the
JDBC API
The developer never uses any proprietary APIs
• Any proprietary APIs are implemented by a JDBC
driver
• There are 4 types of JDBC Drivers
Java Application
JDBC API
JDBC DriverManager
JDBC Driver JDBC Driver
7 viska@unsyiah.ac.id
JDBC Drivers
8 viska@unsyiah.ac.id
JDBC Drivers
 There are 4 types of JDBC Drivers:
 Type 1 - JDBC-ODBC Bridge
 Type 2 - JDBC-Native Bridge
 Type 3 - JDBC-Net Bridge
 Type 4 - Direct JDBC Driver
 Type 1 only runs on platforms where ODBC is available
 ODBC must be configured separately
 Type 2 Drivers map between a proprietary Database API
and the JDBC API
 Type 3 Drivers are used with middleware products
 Type 4 Drivers are written in Java
 In most cases, type 4 drivers are preferred
9 viska@unsyiah.ac.id
JDBC Driver Types
10 viska@unsyiah.ac.id
Type 1: JDBC-ODBC Bridge Driver
 This is an approach wherein the implemented class in Java makes
calls to the code written in Microsoft languages (native), which
speaks directly to the database.
 The first category of JDBC drivers provides a bridge between the
JDBC and the ODBC API . The bridge translates the standard JDBC
calls and sends them to the ODBC data source via ODBC libraries .
 Type 1 drivers use a bridge technology to connect a Java client to an
ODBC database system. The JDBC-ODBC Bridge from Sun and
InterSolv is the only extant example of a Type 1 driver. Type 1 drivers
require some sort of non-Java software to be installed on the
machine running your code, and they are implemented using native
code.
11 viska@unsyiah.ac.id
Type 2: JDBC-Native API
 In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls
which are unique to the database. These drivers typically provided by the
database vendors and used in the same manner as the JDBC-ODBC Bridge,
the vendor-specific driver must be installed on each client machine.
 This is an approach wherein the implemented class in Java makes calls to
the code written from the database provider (native), which speaks directly to
the database.
 If we change the Database we have to change the native API as it is specific
to a database and they are mostly obsolete now but you may realize some
speed increase with a Type 2 driver, because it eliminates ODBC's
overhead.
 The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
12 viska@unsyiah.ac.id
Type 3: JDBC-Net pure Java
 In a Type 3 driver, a three-tier approach is used to accessing databases. The
JDBC clients use standard network sockets to communicate with an
middleware application server. The socket information is then translated by
the middleware application server into the call format required by the DBMS,
and forwarded to the database server.
 You can think of the application server as a JDBC "proxy," meaning that it
makes calls for the client application. As a result, you need some knowledge
of the application server's configuration in order to effectively use this driver
type.
 The Java client application sends a JDBC calls through a JDBC driver to the
intermediate data access server ,which completes the request to the data
source using another driver . This driver uses a database independent
protocol , to communicate database request to a server component which
then translate the request into a DB specific protocol .
13 viska@unsyiah.ac.id
Type 4: 100% pure Java
 In a Type 4 driver, a pure Java-based driver that communicates directly with
vendor's database through socket connection. This is the highest
performance driver available for the database and is usually provided by the
vendor itself.
 This kind of driver is extremely flexible, you don't need to install special
software on the client or server. Further, these drivers can be downloaded
dynamically.
 This is an approach wherein the implemented class in Java (implemented by
the database provider) speaks directly to the database. In other words , it is
a pure Java library that translates JDBC request directly to a Database
specific protocol .
 MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary
nature of their network protocols, database vendors usually supply type 4
drivers.
14 viska@unsyiah.ac.id
So which driver?
 If you are accessing one type of database, such as
Oracle, Sybase, or IBM, the preferred driver type is
4.
 If your Java application is accessing multiple types of
databases at the same time, type 3 is the preferred
driver.
 Type 2 drivers are useful in situations where a type 3
or type 4 driver is not available yet for your
database.
 The type 1 driver is not considered a deployment-
level driver and is typically used for development and
testing purposes only.
15 viska@unsyiah.ac.id
Package java.sql
16 viska@unsyiah.ac.id
JDBC Components
17 viska@unsyiah.ac.id
JDBC Classes
 DriverManager
 Manages JDBC Drivers
 Used to Obtain a connection to a Database
 Types
 Defines constants which identify SQL types
 Date
 Used to Map between java.util.Date and the SQL DATE type
 Time
 Used to Map between java.util.Date and the SQL TIME type
 TimeStamp
 Used to Map between java.util.Date and the SQL TIMESTAMP
type
18 viska@unsyiah.ac.id
JDBC Interfaces
 Driver
 All JDBC Drivers must implement the Driver interface.
Used to obtain a connection to a specific database type
 Connection
 Represents a connection to a specific database
 Used for creating statements
 Used for managing database transactions
 Used for accessing stored procedures
 Used for creating callable statements
 Statement
 Used for executing SQL statements against the database
19 viska@unsyiah.ac.id
JDBC Interfaces
 ResultSet
 Represents the result of an SQL statement
 Provides methods for navigating through the resulting data
 PreparedStatement
 Similar to a stored procedure
 An SQL statement (which can contain parameters) is compiled
and stored in the database
 CallableStatement
 Used for executing stored procedures
 DatabaseMetaData
 Provides access to a database's system catalogue
 ResultSetMetaData
 Provides information about the data contained within a
ResultSet
20 viska@unsyiah.ac.id
Cara Menggunakan JDBC
21 viska@unsyiah.ac.id
Using JDBC
 To execute a statement against a database, the following flow is
observed
 Load the driver (Only performed once)
 Obtain a Connection to the database (Save for later use)
 Obtain a Statement object from the Connection
 Use the Statement object to execute SQL. Updates, inserts and deletes
return Boolean. Selects return a ResultSet
 Navigate ResultSet, using data as required
 Close ResultSet
 Close Statement
 Do NOT close the connection
 The same connection object can be used to create further statements
 A Connection may only have one active Statement at a time. Do not
forget to close the statement when it is no longer needed.
 Close the connection when you no longer need to access the database
22 viska@unsyiah.ac.id
Query
Close
Connect
Process
results
Overview of Querying a Database With
JDBC
23 viska@unsyiah.ac.id
Query
Close
Connect
Process
results
Register the driver
Connect to the database
Stage 1: Connect
24 viska@unsyiah.ac.id
 Is an interpreter that translates JDBC method calls to
vendor-specific database commands
 Implements interfaces in java.sql
 Can also provide a vendor’s extensions to the JDBC
standard
Driver
JDBC calls
Database
commands
Database
A JDBC Driver
25 viska@unsyiah.ac.id
About JDBC URLs
 JDBC uses a URL to identify the database
connection.
jdbc:<subprotocol>:<subname>
Protocol
Database
identifier
jdbc:oracle:<driver>:@<database>
Subprotocol
26 viska@unsyiah.ac.id
Nama URL database:
 JDBC-ODBC :
jdbc:odbc:nama_database
 Oracle :
jdbc:oracle:thin:@nama_host:1521:namaDB
 MySQL:
jdbc:mysql://nama_host:3306/namaDB
 PostgreSQL:
jdbc:postgresql://nama_host:5432/namaDB
 Microsoft SQLServer 2000 :
jdbc:microsoft:sqlserver://nama_host:1433;DatabaseName=n
amaDB
27 viska@unsyiah.ac.id
 Thin driver
 OCI driver
 Server-side driver: Use the default connection
jdbc:oracle:thin:@<host>:<port>:<SID>
jdbc:oracle:oci8:@<TNSNAMES entry>
JDBC URLs with Oracle Drivers
28 viska@unsyiah.ac.id
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection
(URL, userid, password);
ConnectionConnection connconn ==
DriverManager.getConnectionDriverManager.getConnection("("jdbc:mysqljdbc:mysql://://locloc
alhostalhost/books", "root", "/books", "root", "mysqlmysql");");
2. Connect to the database.
How to Make the Connection
1. Register the driver.
29 viska@unsyiah.ac.id
Using Connection
java.sql.Connection Creating Statement
Transaction Management
Get database metadata
Connection related
createStatement()
prepareStatement(String)
prepareCall(String)
commit()
rollback()
getMetaData()
close()
isClosed()
30 viska@unsyiah.ac.id
Close
Connect
Query Create a statement
Process
results
Query the database
Stage 2: Query
31 viska@unsyiah.ac.id
The Statement Object
 A Statement object sends your SQL statement to the
database.
 You need an active connection to create a JDBC
statement.
 Statement has three methods to execute a SQL
statement:
 executeQuery() for QUERY statements
 executeUpdate() for INSERT, UPDATE, DELETE, or
DDL statements
 execute() for either type of statement
32 viska@unsyiah.ac.id
1. Create an empty statement object.
2. Execute the statement.
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery(statement);
int count = stmt.executeUpdate(statement);
boolean isquery = stmt.execute(statement);
How to Query the Database
33 viska@unsyiah.ac.id
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery
("select RENTAL_ID, STATUS from ACME_RENTALS");
Statement stmt = conn.createStatement();
int rowcount = stmt.executeUpdate
("delete from ACME_RENTAL_ITEMS
where rental_id = 1011");
Querying the Database: Examples
 Execute a select statement.
• Execute a delete statement.
34 viska@unsyiah.ac.id
Close
Query
Step through the results
Process
results
Assign results to Java
variables
Connect
Stage 3: Process the Results
35 viska@unsyiah.ac.id
The ResultSet Object
 JDBC returns the results of a query in a ResultSet
object.
 A ResultSet maintains a cursor pointing to its current
row of data.
 Use next() to step through the result set row by row.
 getString(), getInt(), and so on assign each value to
a Java variable.
36 viska@unsyiah.ac.id
while (rset.next()) { … }
String val =
rset.getString(colname);
while (rset.next()) {
String title = rset.getString("TITLE");
String year = rset.getString("YEAR");
… // Process or display the data
}
String val =
rset.getString(colIndex);
How to Process the Results
 1. Step through the result set.
 2. Use getXXX() to get each column value.
37 viska@unsyiah.ac.id
while (rset.next()) {
String year = rset.getString("YEAR");
if (rset.wasNull() {
… // Handle null value
}
…}
How to Handle SQL Null Values
 Java primitive types cannot have null values.
 Do not use a primitive type when your query
might return a SQL null.
 Use ResultSet.wasNull() to determine whether a
column has a null value.
38 viska@unsyiah.ac.id
Mapping Database Types to Java Types
 ResultSet maps database types to Java types.
ResultSet rset = stmt.executeQuery
("select RENTAL_ID, RENTAL_DATE, STATUS
from ACME_RENTALS");
int id = rset.getInt(1);
Date rentaldate = rset.getDate(2);
String status = rset.getString(3);
Col Name
RENTAL_ID
RENTAL_DATE
STATUS
Type
NUMBER
DATE
VARCHAR239 viska@unsyiah.ac.id
SQL Types/Java Types Mapping
SQL Type Java Type
CHAR String
VARCHAR String
LONGVARCHAR String
NUMERIC java.Math.BigDecimal
DECIMAL java.Math.BigDecimal
BIT boolean
TINYINT int
SMALLINT int
INTEGER int
BIGINT long
REAL float
FLOAT double
DOUBLE double
BINARY byte[]
VARBINARY byte[]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
40 viska@unsyiah.ac.id
Connect
Query
Process
results
Close
Close the result set
Close the statement
Close the connection
Stage 4: Close
41 viska@unsyiah.ac.id
1. Close the ResultSet object.
2. Close the Statement object.
3. Close the connection (not necessary for server-side
driver).
rset.close();
stmt.close();
conn.close();
How to Close the Connection
42 viska@unsyiah.ac.id
Connection aConnection;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException x)
{
System.out.println("Cannot find driver class. Check CLASSPATH");
return;
}
try
{
aConnection = DriverManager.getConnection("jdbc:odbc:MyDatabase",
"Username", "Password");
}
catch(SQLException x)
{
System.out.println("Exception connecting to database:" + x);
return;
}
Example Code:
43 viska@unsyiah.ac.id
try
{
Statement aStmt = aConnection.createStatement();
StringBuffer sb = new StringBuffer("SELECT Employee_id, Employee_Name");
sb.append(" FROM Employee WHERE EmployeeId>100");
ResultSet rs = aStmt.executeQuery(sb.toString());
while(rs.next())
{
int employeeId = rs.getInt(1);
String employeeName = rs.getString(2);
System.out.println("Id:" + employeeId + "nName:" + employeeName);
}
rs.close();
aStmt.close();
}
catch(SQLException x)
{
System.out.println("Exception while executing query:" + x);
}
Example Code (continued):
44 viska@unsyiah.ac.id
More Advanced
Dynamic Query using MetaData
45 viska@unsyiah.ac.id
The DatabaseMetaData Object
 The Connection object can be used to get a
DatabaseMetaData object.
 This object provides more than 100 methods to
obtain information about the database.
46 viska@unsyiah.ac.id
1. Get the DatabaseMetaData object.
2. Use the object’s methods to get the metadata.
DatabaseMetaData dbmd = conn.getMetaData();
String s1 = dbmd getURL();
String s2 = dbmd.getSQLKeywords();
boolean b1 = dbmd.supportsTransactions();
boolean b2 = dbmd.supportsSelectForUpdate();
How to Obtain Database Metadata
DatabaseMetaData dbmd = conn.getMetaData();
47 viska@unsyiah.ac.id
The ResultSetMetaData Object
 The ResultSet object can be used to get a
ResultSetMetaData object.
 ResultSetMetaData object provides metadata,
including:
 Number of columns in the result set
 Column type
 Column name
48 viska@unsyiah.ac.id
How to Obtain Result Set Metadata
1. Get the ResultSetMetaData object.
2. Use the object’s methods to get the metadata.
ResultSetMetaData rsmd = rset.getMetaData();
for (int i = 0; i < rsmd.getColumnCount(); i++)
{
String colname = rsmd.getColumnName(i);
int coltype = rsmd.getColumnType(i);
…
}
ResultSetMetaData rsmd = rset.getMetaData();
49 viska@unsyiah.ac.id
The PreparedStatement Object
 A PreparedStatement object
holds precompiled SQL statements.
 Use this object for statements you want to execute
more than once.
 A prepared statement can contain variables that you
supply each time you execute the statement.
50 viska@unsyiah.ac.id
How to Create a Prepared Statement
1.Register the driver and create the database
connection.
2.Create the prepared statement, identifying variables
with a question mark (?).
PreparedStatement pstmt =
conn.prepareStatement("update ACME_RENTALS
set STATUS = ? where RENTAL_ID = ?");
PreparedStatement pstmt =
conn.prepareStatement("select STATUS from
ACME_RENTALS where RENTAL_ID = ?");
51 viska@unsyiah.ac.id
How to Execute a Prepared Statement
1. Supply values for the variables.
2. Execute the statement.
pstmt.setXXX(index, value);
pstmt.executeQuery();
pstmt.executeUpdate();
PreparedStatement pstmt =
conn.prepareStatement("update ACME_RENTALS
set STATUS = ? where RENTAL_ID = ?");
pstmt.setString(1, "OUT");
pstmt.setInt(2, rentalid);
pstmt.executeUpdate();
52 viska@unsyiah.ac.id
The CallableStatement Object
 A CallableStatement object holds parameters for
calling stored procedures.
 A callable statement can contain variables that you
supply each time you execute the call.
 When the stored procedure returns, computed
values (if any) are retrieved through the
CallabableStatement object.
53 viska@unsyiah.ac.id
 Register the driver and create the database
connection.
 Create the callable statement, identifying variables
with a question mark (?).
CallableStatement cstmt =
conn.prepareCall("{call " +
ADDITEM + "(?,?,?)}");
cstmt.registerOutParameter(2,Types.INTEGER);
cStmt.registerOutParameter(3,Types.DOUBLE);
How to Create a Callable Statement
54 viska@unsyiah.ac.id
1. Set the input parameters.
2. Execute the statement.
3. Get the output parameters.
How to Execute a Callable Statement
cstmt.setXXX(index, value);
cstmt.execute(statement);
var = cstmt.getXXX(index);
55 viska@unsyiah.ac.id
Using Transactions
 The server-side driver does not support autocommit
mode.
 With other drivers:
 New connections are in autocommit mode.
 Use conn.setAutoCommit(false) to turn autocommit
off.
 To control transactions when you are not in
autocommit mode:
 conn.commit(): Commit a transaction
 conn.rollback(): Roll back a transaction
56 viska@unsyiah.ac.id
57 viska@unsyiah.ac.id

More Related Content

What's hot

What's hot (20)

Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)
 
Jdbc
JdbcJdbc
Jdbc
 
java Jdbc
java Jdbc java Jdbc
java Jdbc
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
JDBC Architecture and Drivers
JDBC Architecture and DriversJDBC Architecture and Drivers
JDBC Architecture and Drivers
 
Jdbc drivers
Jdbc driversJdbc drivers
Jdbc drivers
 
Jdbc slide for beginers
Jdbc slide for beginersJdbc slide for beginers
Jdbc slide for beginers
 
Jdbc driver types
Jdbc driver typesJdbc driver types
Jdbc driver types
 
Ajp notes-chapter-05
Ajp notes-chapter-05Ajp notes-chapter-05
Ajp notes-chapter-05
 
JDBC-Introduction
JDBC-IntroductionJDBC-Introduction
JDBC-Introduction
 
Jdbc
JdbcJdbc
Jdbc
 
Database and Java Database Connectivity
Database and Java Database ConnectivityDatabase and Java Database Connectivity
Database and Java Database Connectivity
 
Overview Of JDBC
Overview Of JDBCOverview Of JDBC
Overview Of JDBC
 
Jdbc_ravi_2016
Jdbc_ravi_2016Jdbc_ravi_2016
Jdbc_ravi_2016
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet Solution
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
 
Core jdbc basics
Core jdbc basicsCore jdbc basics
Core jdbc basics
 
Unit 5-jdbc2
Unit 5-jdbc2Unit 5-jdbc2
Unit 5-jdbc2
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Rajesh jdbc
Rajesh   jdbcRajesh   jdbc
Rajesh jdbc
 

Similar to 3 jdbc

Chapter_4_-_JDBC[1].pptx
Chapter_4_-_JDBC[1].pptxChapter_4_-_JDBC[1].pptx
Chapter_4_-_JDBC[1].pptxBachaSirata
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityVaishali Modi
 
JDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptJDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptkingkolju
 
JDBC java database connectivity with dbms
JDBC java database connectivity with dbmsJDBC java database connectivity with dbms
JDBC java database connectivity with dbmsKhyalNayak
 
java.pptx
java.pptxjava.pptx
java.pptxbfgd1
 
chapter 5 java.pptx
chapter 5  java.pptxchapter 5  java.pptx
chapter 5 java.pptxBekiTube
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Pooja Talreja
 
4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.pptNaveenKumar648465
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdfArumugam90
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdfArumugam90
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySqlDhyey Dattani
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySqlDhyey Dattani
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)Fad Zulkifli
 

Similar to 3 jdbc (20)

Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 
Chapter_4_-_JDBC[1].pptx
Chapter_4_-_JDBC[1].pptxChapter_4_-_JDBC[1].pptx
Chapter_4_-_JDBC[1].pptx
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
JDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptJDBC java for learning java for learn.ppt
JDBC java for learning java for learn.ppt
 
JDBC java database connectivity with dbms
JDBC java database connectivity with dbmsJDBC java database connectivity with dbms
JDBC java database connectivity with dbms
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
 
java.pptx
java.pptxjava.pptx
java.pptx
 
chapter 5 java.pptx
chapter 5  java.pptxchapter 5  java.pptx
chapter 5 java.pptx
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
 
JDBC
JDBCJDBC
JDBC
 
jdbc
jdbcjdbc
jdbc
 
4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Vinay
VinayVinay
Vinay
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
 

More from Fajar Baskoro

Generasi Terampil Digital Skill-2023.pptx
Generasi Terampil Digital Skill-2023.pptxGenerasi Terampil Digital Skill-2023.pptx
Generasi Terampil Digital Skill-2023.pptxFajar Baskoro
 
Cara Membuat Kursus Online Wordpress-tutorstarter
Cara Membuat Kursus Online Wordpress-tutorstarterCara Membuat Kursus Online Wordpress-tutorstarter
Cara Membuat Kursus Online Wordpress-tutorstarterFajar Baskoro
 
PPT-Kick Off Double Track 2024 melaksanakan Festival Ramadhan
PPT-Kick Off Double Track 2024 melaksanakan Festival RamadhanPPT-Kick Off Double Track 2024 melaksanakan Festival Ramadhan
PPT-Kick Off Double Track 2024 melaksanakan Festival RamadhanFajar Baskoro
 
Buku Inovasi 2023 - 2024 konsep capaian KUS
Buku Inovasi 2023 - 2024 konsep capaian  KUSBuku Inovasi 2023 - 2024 konsep capaian  KUS
Buku Inovasi 2023 - 2024 konsep capaian KUSFajar Baskoro
 
Pemaparan Sosialisasi Program Dual Track 2024.pptx
Pemaparan Sosialisasi Program Dual Track 2024.pptxPemaparan Sosialisasi Program Dual Track 2024.pptx
Pemaparan Sosialisasi Program Dual Track 2024.pptxFajar Baskoro
 
Executive Millennial Entrepreneur Award 2023-1a-1.pdf
Executive Millennial Entrepreneur Award  2023-1a-1.pdfExecutive Millennial Entrepreneur Award  2023-1a-1.pdf
Executive Millennial Entrepreneur Award 2023-1a-1.pdfFajar Baskoro
 
1-Executive Millennial Entrepreneur Award 2023-1-cetak.pptx
1-Executive Millennial Entrepreneur Award  2023-1-cetak.pptx1-Executive Millennial Entrepreneur Award  2023-1-cetak.pptx
1-Executive Millennial Entrepreneur Award 2023-1-cetak.pptxFajar Baskoro
 
Executive Millennial Entrepreneur Award 2023-1.pptx
Executive Millennial Entrepreneur Award  2023-1.pptxExecutive Millennial Entrepreneur Award  2023-1.pptx
Executive Millennial Entrepreneur Award 2023-1.pptxFajar Baskoro
 
Pemrograman Mobile - JetPack Compose1.pptx
Pemrograman Mobile - JetPack Compose1.pptxPemrograman Mobile - JetPack Compose1.pptx
Pemrograman Mobile - JetPack Compose1.pptxFajar Baskoro
 
Evaluasi KPP Program Dual Track Provinsi Kaltim
Evaluasi KPP Program Dual Track Provinsi KaltimEvaluasi KPP Program Dual Track Provinsi Kaltim
Evaluasi KPP Program Dual Track Provinsi KaltimFajar Baskoro
 
foto tenda digital skill program dari sekolah
foto tenda digital skill program dari sekolahfoto tenda digital skill program dari sekolah
foto tenda digital skill program dari sekolahFajar Baskoro
 
Meraih Peluang di Gig Economy yang cocok bagi remaja
Meraih Peluang di Gig Economy yang cocok bagi remajaMeraih Peluang di Gig Economy yang cocok bagi remaja
Meraih Peluang di Gig Economy yang cocok bagi remajaFajar Baskoro
 
Membangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan AppsheetMembangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan AppsheetFajar Baskoro
 
Transition education to employment.pdf
Transition education to employment.pdfTransition education to employment.pdf
Transition education to employment.pdfFajar Baskoro
 

More from Fajar Baskoro (20)

Generasi Terampil Digital Skill-2023.pptx
Generasi Terampil Digital Skill-2023.pptxGenerasi Terampil Digital Skill-2023.pptx
Generasi Terampil Digital Skill-2023.pptx
 
Cara Membuat Kursus Online Wordpress-tutorstarter
Cara Membuat Kursus Online Wordpress-tutorstarterCara Membuat Kursus Online Wordpress-tutorstarter
Cara Membuat Kursus Online Wordpress-tutorstarter
 
PPT-Kick Off Double Track 2024 melaksanakan Festival Ramadhan
PPT-Kick Off Double Track 2024 melaksanakan Festival RamadhanPPT-Kick Off Double Track 2024 melaksanakan Festival Ramadhan
PPT-Kick Off Double Track 2024 melaksanakan Festival Ramadhan
 
Buku Inovasi 2023 - 2024 konsep capaian KUS
Buku Inovasi 2023 - 2024 konsep capaian  KUSBuku Inovasi 2023 - 2024 konsep capaian  KUS
Buku Inovasi 2023 - 2024 konsep capaian KUS
 
Pemaparan Sosialisasi Program Dual Track 2024.pptx
Pemaparan Sosialisasi Program Dual Track 2024.pptxPemaparan Sosialisasi Program Dual Track 2024.pptx
Pemaparan Sosialisasi Program Dual Track 2024.pptx
 
Executive Millennial Entrepreneur Award 2023-1a-1.pdf
Executive Millennial Entrepreneur Award  2023-1a-1.pdfExecutive Millennial Entrepreneur Award  2023-1a-1.pdf
Executive Millennial Entrepreneur Award 2023-1a-1.pdf
 
1-Executive Millennial Entrepreneur Award 2023-1-cetak.pptx
1-Executive Millennial Entrepreneur Award  2023-1-cetak.pptx1-Executive Millennial Entrepreneur Award  2023-1-cetak.pptx
1-Executive Millennial Entrepreneur Award 2023-1-cetak.pptx
 
Executive Millennial Entrepreneur Award 2023-1.pptx
Executive Millennial Entrepreneur Award  2023-1.pptxExecutive Millennial Entrepreneur Award  2023-1.pptx
Executive Millennial Entrepreneur Award 2023-1.pptx
 
Pemrograman Mobile - JetPack Compose1.pptx
Pemrograman Mobile - JetPack Compose1.pptxPemrograman Mobile - JetPack Compose1.pptx
Pemrograman Mobile - JetPack Compose1.pptx
 
Evaluasi KPP Program Dual Track Provinsi Kaltim
Evaluasi KPP Program Dual Track Provinsi KaltimEvaluasi KPP Program Dual Track Provinsi Kaltim
Evaluasi KPP Program Dual Track Provinsi Kaltim
 
foto tenda digital skill program dari sekolah
foto tenda digital skill program dari sekolahfoto tenda digital skill program dari sekolah
foto tenda digital skill program dari sekolah
 
Meraih Peluang di Gig Economy yang cocok bagi remaja
Meraih Peluang di Gig Economy yang cocok bagi remajaMeraih Peluang di Gig Economy yang cocok bagi remaja
Meraih Peluang di Gig Economy yang cocok bagi remaja
 
Membangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan AppsheetMembangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan Appsheet
 
epl1.pdf
epl1.pdfepl1.pdf
epl1.pdf
 
user.docx
user.docxuser.docx
user.docx
 
Dtmart.pptx
Dtmart.pptxDtmart.pptx
Dtmart.pptx
 
DualTrack-2023.pptx
DualTrack-2023.pptxDualTrack-2023.pptx
DualTrack-2023.pptx
 
BADGE.pptx
BADGE.pptxBADGE.pptx
BADGE.pptx
 
womenatwork.pdf
womenatwork.pdfwomenatwork.pdf
womenatwork.pdf
 
Transition education to employment.pdf
Transition education to employment.pdfTransition education to employment.pdf
Transition education to employment.pdf
 

Recently uploaded

Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 

Recently uploaded (20)

Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 

3 jdbc

  • 1. JDBC Prepared by Viska Mutiawani 1 viska@unsyiah.ac.id
  • 2. Subtopik JDBC  Pengenalan JDBC  JDBC driver  Package java.sql  Cara menggunakan JDBC  Advance 2 viska@unsyiah.ac.id
  • 4. JDBC – Java Database Connectivity  JDBC is a standard interface for connecting to relational databases from Java.  The JDBC classes and interfaces are in the java.sql package.  JDBC 1.22 is part of JDK 1.1; JDBC 2.0 is part of Java 2 4 viska@unsyiah.ac.id
  • 5. Apakah itu JDBC?  JDBC provides Java applications with access to most database systems via SQL  The architecture and API closely resemble Microsoft's ODBC  JDBC 1.0 was originally introduced into Java 1.1  JDBC 2.0 was added to Java 1.2  JDBC is based on SQL-92  JDBC classes are contained within the java.sql package  There are few classes  There are several interfaces 5 viska@unsyiah.ac.id
  • 6. Database connectivity history  Before APIs like JDBC and ODBC, database connectivity was tedious  Each database vendor provided a function library for accessing their database  The connectivity library was proprietary.  If the database vendor changed for the application, the data access portions had to be rewritten  If the application was poorly structured, rewriting its data access might involve rewriting the majority of the application  The costs incurred generally meant that application developers were stuck with a particular database product for a given application 6 viska@unsyiah.ac.id
  • 7. Arsitektur JDBC With JDBC, the application programmer uses the JDBC API The developer never uses any proprietary APIs • Any proprietary APIs are implemented by a JDBC driver • There are 4 types of JDBC Drivers Java Application JDBC API JDBC DriverManager JDBC Driver JDBC Driver 7 viska@unsyiah.ac.id
  • 9. JDBC Drivers  There are 4 types of JDBC Drivers:  Type 1 - JDBC-ODBC Bridge  Type 2 - JDBC-Native Bridge  Type 3 - JDBC-Net Bridge  Type 4 - Direct JDBC Driver  Type 1 only runs on platforms where ODBC is available  ODBC must be configured separately  Type 2 Drivers map between a proprietary Database API and the JDBC API  Type 3 Drivers are used with middleware products  Type 4 Drivers are written in Java  In most cases, type 4 drivers are preferred 9 viska@unsyiah.ac.id
  • 10. JDBC Driver Types 10 viska@unsyiah.ac.id
  • 11. Type 1: JDBC-ODBC Bridge Driver  This is an approach wherein the implemented class in Java makes calls to the code written in Microsoft languages (native), which speaks directly to the database.  The first category of JDBC drivers provides a bridge between the JDBC and the ODBC API . The bridge translates the standard JDBC calls and sends them to the ODBC data source via ODBC libraries .  Type 1 drivers use a bridge technology to connect a Java client to an ODBC database system. The JDBC-ODBC Bridge from Sun and InterSolv is the only extant example of a Type 1 driver. Type 1 drivers require some sort of non-Java software to be installed on the machine running your code, and they are implemented using native code. 11 viska@unsyiah.ac.id
  • 12. Type 2: JDBC-Native API  In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls which are unique to the database. These drivers typically provided by the database vendors and used in the same manner as the JDBC-ODBC Bridge, the vendor-specific driver must be installed on each client machine.  This is an approach wherein the implemented class in Java makes calls to the code written from the database provider (native), which speaks directly to the database.  If we change the Database we have to change the native API as it is specific to a database and they are mostly obsolete now but you may realize some speed increase with a Type 2 driver, because it eliminates ODBC's overhead.  The Oracle Call Interface (OCI) driver is an example of a Type 2 driver. 12 viska@unsyiah.ac.id
  • 13. Type 3: JDBC-Net pure Java  In a Type 3 driver, a three-tier approach is used to accessing databases. The JDBC clients use standard network sockets to communicate with an middleware application server. The socket information is then translated by the middleware application server into the call format required by the DBMS, and forwarded to the database server.  You can think of the application server as a JDBC "proxy," meaning that it makes calls for the client application. As a result, you need some knowledge of the application server's configuration in order to effectively use this driver type.  The Java client application sends a JDBC calls through a JDBC driver to the intermediate data access server ,which completes the request to the data source using another driver . This driver uses a database independent protocol , to communicate database request to a server component which then translate the request into a DB specific protocol . 13 viska@unsyiah.ac.id
  • 14. Type 4: 100% pure Java  In a Type 4 driver, a pure Java-based driver that communicates directly with vendor's database through socket connection. This is the highest performance driver available for the database and is usually provided by the vendor itself.  This kind of driver is extremely flexible, you don't need to install special software on the client or server. Further, these drivers can be downloaded dynamically.  This is an approach wherein the implemented class in Java (implemented by the database provider) speaks directly to the database. In other words , it is a pure Java library that translates JDBC request directly to a Database specific protocol .  MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their network protocols, database vendors usually supply type 4 drivers. 14 viska@unsyiah.ac.id
  • 15. So which driver?  If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is 4.  If your Java application is accessing multiple types of databases at the same time, type 3 is the preferred driver.  Type 2 drivers are useful in situations where a type 3 or type 4 driver is not available yet for your database.  The type 1 driver is not considered a deployment- level driver and is typically used for development and testing purposes only. 15 viska@unsyiah.ac.id
  • 18. JDBC Classes  DriverManager  Manages JDBC Drivers  Used to Obtain a connection to a Database  Types  Defines constants which identify SQL types  Date  Used to Map between java.util.Date and the SQL DATE type  Time  Used to Map between java.util.Date and the SQL TIME type  TimeStamp  Used to Map between java.util.Date and the SQL TIMESTAMP type 18 viska@unsyiah.ac.id
  • 19. JDBC Interfaces  Driver  All JDBC Drivers must implement the Driver interface. Used to obtain a connection to a specific database type  Connection  Represents a connection to a specific database  Used for creating statements  Used for managing database transactions  Used for accessing stored procedures  Used for creating callable statements  Statement  Used for executing SQL statements against the database 19 viska@unsyiah.ac.id
  • 20. JDBC Interfaces  ResultSet  Represents the result of an SQL statement  Provides methods for navigating through the resulting data  PreparedStatement  Similar to a stored procedure  An SQL statement (which can contain parameters) is compiled and stored in the database  CallableStatement  Used for executing stored procedures  DatabaseMetaData  Provides access to a database's system catalogue  ResultSetMetaData  Provides information about the data contained within a ResultSet 20 viska@unsyiah.ac.id
  • 21. Cara Menggunakan JDBC 21 viska@unsyiah.ac.id
  • 22. Using JDBC  To execute a statement against a database, the following flow is observed  Load the driver (Only performed once)  Obtain a Connection to the database (Save for later use)  Obtain a Statement object from the Connection  Use the Statement object to execute SQL. Updates, inserts and deletes return Boolean. Selects return a ResultSet  Navigate ResultSet, using data as required  Close ResultSet  Close Statement  Do NOT close the connection  The same connection object can be used to create further statements  A Connection may only have one active Statement at a time. Do not forget to close the statement when it is no longer needed.  Close the connection when you no longer need to access the database 22 viska@unsyiah.ac.id
  • 23. Query Close Connect Process results Overview of Querying a Database With JDBC 23 viska@unsyiah.ac.id
  • 24. Query Close Connect Process results Register the driver Connect to the database Stage 1: Connect 24 viska@unsyiah.ac.id
  • 25.  Is an interpreter that translates JDBC method calls to vendor-specific database commands  Implements interfaces in java.sql  Can also provide a vendor’s extensions to the JDBC standard Driver JDBC calls Database commands Database A JDBC Driver 25 viska@unsyiah.ac.id
  • 26. About JDBC URLs  JDBC uses a URL to identify the database connection. jdbc:<subprotocol>:<subname> Protocol Database identifier jdbc:oracle:<driver>:@<database> Subprotocol 26 viska@unsyiah.ac.id
  • 27. Nama URL database:  JDBC-ODBC : jdbc:odbc:nama_database  Oracle : jdbc:oracle:thin:@nama_host:1521:namaDB  MySQL: jdbc:mysql://nama_host:3306/namaDB  PostgreSQL: jdbc:postgresql://nama_host:5432/namaDB  Microsoft SQLServer 2000 : jdbc:microsoft:sqlserver://nama_host:1433;DatabaseName=n amaDB 27 viska@unsyiah.ac.id
  • 28.  Thin driver  OCI driver  Server-side driver: Use the default connection jdbc:oracle:thin:@<host>:<port>:<SID> jdbc:oracle:oci8:@<TNSNAMES entry> JDBC URLs with Oracle Drivers 28 viska@unsyiah.ac.id
  • 29. Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection (URL, userid, password); ConnectionConnection connconn == DriverManager.getConnectionDriverManager.getConnection("("jdbc:mysqljdbc:mysql://://locloc alhostalhost/books", "root", "/books", "root", "mysqlmysql");"); 2. Connect to the database. How to Make the Connection 1. Register the driver. 29 viska@unsyiah.ac.id
  • 30. Using Connection java.sql.Connection Creating Statement Transaction Management Get database metadata Connection related createStatement() prepareStatement(String) prepareCall(String) commit() rollback() getMetaData() close() isClosed() 30 viska@unsyiah.ac.id
  • 31. Close Connect Query Create a statement Process results Query the database Stage 2: Query 31 viska@unsyiah.ac.id
  • 32. The Statement Object  A Statement object sends your SQL statement to the database.  You need an active connection to create a JDBC statement.  Statement has three methods to execute a SQL statement:  executeQuery() for QUERY statements  executeUpdate() for INSERT, UPDATE, DELETE, or DDL statements  execute() for either type of statement 32 viska@unsyiah.ac.id
  • 33. 1. Create an empty statement object. 2. Execute the statement. Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery(statement); int count = stmt.executeUpdate(statement); boolean isquery = stmt.execute(statement); How to Query the Database 33 viska@unsyiah.ac.id
  • 34. Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery ("select RENTAL_ID, STATUS from ACME_RENTALS"); Statement stmt = conn.createStatement(); int rowcount = stmt.executeUpdate ("delete from ACME_RENTAL_ITEMS where rental_id = 1011"); Querying the Database: Examples  Execute a select statement. • Execute a delete statement. 34 viska@unsyiah.ac.id
  • 35. Close Query Step through the results Process results Assign results to Java variables Connect Stage 3: Process the Results 35 viska@unsyiah.ac.id
  • 36. The ResultSet Object  JDBC returns the results of a query in a ResultSet object.  A ResultSet maintains a cursor pointing to its current row of data.  Use next() to step through the result set row by row.  getString(), getInt(), and so on assign each value to a Java variable. 36 viska@unsyiah.ac.id
  • 37. while (rset.next()) { … } String val = rset.getString(colname); while (rset.next()) { String title = rset.getString("TITLE"); String year = rset.getString("YEAR"); … // Process or display the data } String val = rset.getString(colIndex); How to Process the Results  1. Step through the result set.  2. Use getXXX() to get each column value. 37 viska@unsyiah.ac.id
  • 38. while (rset.next()) { String year = rset.getString("YEAR"); if (rset.wasNull() { … // Handle null value } …} How to Handle SQL Null Values  Java primitive types cannot have null values.  Do not use a primitive type when your query might return a SQL null.  Use ResultSet.wasNull() to determine whether a column has a null value. 38 viska@unsyiah.ac.id
  • 39. Mapping Database Types to Java Types  ResultSet maps database types to Java types. ResultSet rset = stmt.executeQuery ("select RENTAL_ID, RENTAL_DATE, STATUS from ACME_RENTALS"); int id = rset.getInt(1); Date rentaldate = rset.getDate(2); String status = rset.getString(3); Col Name RENTAL_ID RENTAL_DATE STATUS Type NUMBER DATE VARCHAR239 viska@unsyiah.ac.id
  • 40. SQL Types/Java Types Mapping SQL Type Java Type CHAR String VARCHAR String LONGVARCHAR String NUMERIC java.Math.BigDecimal DECIMAL java.Math.BigDecimal BIT boolean TINYINT int SMALLINT int INTEGER int BIGINT long REAL float FLOAT double DOUBLE double BINARY byte[] VARBINARY byte[] DATE java.sql.Date TIME java.sql.Time TIMESTAMP java.sql.Timestamp 40 viska@unsyiah.ac.id
  • 41. Connect Query Process results Close Close the result set Close the statement Close the connection Stage 4: Close 41 viska@unsyiah.ac.id
  • 42. 1. Close the ResultSet object. 2. Close the Statement object. 3. Close the connection (not necessary for server-side driver). rset.close(); stmt.close(); conn.close(); How to Close the Connection 42 viska@unsyiah.ac.id
  • 43. Connection aConnection; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException x) { System.out.println("Cannot find driver class. Check CLASSPATH"); return; } try { aConnection = DriverManager.getConnection("jdbc:odbc:MyDatabase", "Username", "Password"); } catch(SQLException x) { System.out.println("Exception connecting to database:" + x); return; } Example Code: 43 viska@unsyiah.ac.id
  • 44. try { Statement aStmt = aConnection.createStatement(); StringBuffer sb = new StringBuffer("SELECT Employee_id, Employee_Name"); sb.append(" FROM Employee WHERE EmployeeId>100"); ResultSet rs = aStmt.executeQuery(sb.toString()); while(rs.next()) { int employeeId = rs.getInt(1); String employeeName = rs.getString(2); System.out.println("Id:" + employeeId + "nName:" + employeeName); } rs.close(); aStmt.close(); } catch(SQLException x) { System.out.println("Exception while executing query:" + x); } Example Code (continued): 44 viska@unsyiah.ac.id
  • 45. More Advanced Dynamic Query using MetaData 45 viska@unsyiah.ac.id
  • 46. The DatabaseMetaData Object  The Connection object can be used to get a DatabaseMetaData object.  This object provides more than 100 methods to obtain information about the database. 46 viska@unsyiah.ac.id
  • 47. 1. Get the DatabaseMetaData object. 2. Use the object’s methods to get the metadata. DatabaseMetaData dbmd = conn.getMetaData(); String s1 = dbmd getURL(); String s2 = dbmd.getSQLKeywords(); boolean b1 = dbmd.supportsTransactions(); boolean b2 = dbmd.supportsSelectForUpdate(); How to Obtain Database Metadata DatabaseMetaData dbmd = conn.getMetaData(); 47 viska@unsyiah.ac.id
  • 48. The ResultSetMetaData Object  The ResultSet object can be used to get a ResultSetMetaData object.  ResultSetMetaData object provides metadata, including:  Number of columns in the result set  Column type  Column name 48 viska@unsyiah.ac.id
  • 49. How to Obtain Result Set Metadata 1. Get the ResultSetMetaData object. 2. Use the object’s methods to get the metadata. ResultSetMetaData rsmd = rset.getMetaData(); for (int i = 0; i < rsmd.getColumnCount(); i++) { String colname = rsmd.getColumnName(i); int coltype = rsmd.getColumnType(i); … } ResultSetMetaData rsmd = rset.getMetaData(); 49 viska@unsyiah.ac.id
  • 50. The PreparedStatement Object  A PreparedStatement object holds precompiled SQL statements.  Use this object for statements you want to execute more than once.  A prepared statement can contain variables that you supply each time you execute the statement. 50 viska@unsyiah.ac.id
  • 51. How to Create a Prepared Statement 1.Register the driver and create the database connection. 2.Create the prepared statement, identifying variables with a question mark (?). PreparedStatement pstmt = conn.prepareStatement("update ACME_RENTALS set STATUS = ? where RENTAL_ID = ?"); PreparedStatement pstmt = conn.prepareStatement("select STATUS from ACME_RENTALS where RENTAL_ID = ?"); 51 viska@unsyiah.ac.id
  • 52. How to Execute a Prepared Statement 1. Supply values for the variables. 2. Execute the statement. pstmt.setXXX(index, value); pstmt.executeQuery(); pstmt.executeUpdate(); PreparedStatement pstmt = conn.prepareStatement("update ACME_RENTALS set STATUS = ? where RENTAL_ID = ?"); pstmt.setString(1, "OUT"); pstmt.setInt(2, rentalid); pstmt.executeUpdate(); 52 viska@unsyiah.ac.id
  • 53. The CallableStatement Object  A CallableStatement object holds parameters for calling stored procedures.  A callable statement can contain variables that you supply each time you execute the call.  When the stored procedure returns, computed values (if any) are retrieved through the CallabableStatement object. 53 viska@unsyiah.ac.id
  • 54.  Register the driver and create the database connection.  Create the callable statement, identifying variables with a question mark (?). CallableStatement cstmt = conn.prepareCall("{call " + ADDITEM + "(?,?,?)}"); cstmt.registerOutParameter(2,Types.INTEGER); cStmt.registerOutParameter(3,Types.DOUBLE); How to Create a Callable Statement 54 viska@unsyiah.ac.id
  • 55. 1. Set the input parameters. 2. Execute the statement. 3. Get the output parameters. How to Execute a Callable Statement cstmt.setXXX(index, value); cstmt.execute(statement); var = cstmt.getXXX(index); 55 viska@unsyiah.ac.id
  • 56. Using Transactions  The server-side driver does not support autocommit mode.  With other drivers:  New connections are in autocommit mode.  Use conn.setAutoCommit(false) to turn autocommit off.  To control transactions when you are not in autocommit mode:  conn.commit(): Commit a transaction  conn.rollback(): Roll back a transaction 56 viska@unsyiah.ac.id