Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
49 views

Chapter 3 - 2016-Java Database Connectivity With JDBC

This chapter discusses Java Database Connectivity (JDBC) which provides a standard interface for connecting Java applications to SQL databases. It covers key JDBC concepts like using drivers to connect to databases, executing SQL statements through JDBC, and processing result sets. The chapter also discusses how to handle exceptions and warnings that can occur.

Uploaded by

Beka Beko
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Chapter 3 - 2016-Java Database Connectivity With JDBC

This chapter discusses Java Database Connectivity (JDBC) which provides a standard interface for connecting Java applications to SQL databases. It covers key JDBC concepts like using drivers to connect to databases, executing SQL statements through JDBC, and processing result sets. The chapter also discusses how to handle exceptions and warnings that can occur.

Uploaded by

Beka Beko
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Advanced Programming Course

Chapter: Three
Java Database connectivity with JDBC

1 Ch-3: JDBC Compiled by: Berhanu A.


Chapter 3
Content outlines
• Introduction
• Relational Database
• SQL
• Creating Database
• Manipulating Database with JDBC
• Stored Procedures

2 Ch-3: JDBC Compiled by: Berhanu A.


1. Introduction
Short for Java Database Connectivity, a Java
API that enables Java programs to execute SQL
statements.
This allows Java programs to interact with any
SQL-compliant database.
Since nearly all
relational database management systems (DBM
Ss)
support SQL, and because Java itself runs on
most platforms, JDBC makes it possible to write
a single database application that can run on
3 different platforms and interact with different
Ch-3: JDBC Compiled by: Berhanu A.
1. Introduction
JDBC stands for “Java DataBase Connectivity”
The standard interface for communication between a Java
application and a SQL database
Allows a Java program to issue SQL statements and
process the results.
JDBC was developed by JavaSoft a subsidiary of Sun
Microsystems.
The JDBC API is a Java API that can access any kind of
tabular data, especially data stored in a Relational
Database.
JDBC is an API defined in the java.sql or javax.sql
4 packages
Ch-3: JDBCfor connecting
Compiled by: Berhanu A.an arbitrary database to the java
Cont…
JDBC is a Java API that provides Java programmers
with a uniform interface for accessing and
manipulating a wide range of relational databases.
With JDBC, you can write database programs that run
on any platform that has a Java Virtual Machine
with an appropriate JDBC driver.
The JDBC API is a set of Java interfaces and classes
used to write Java programs for accessing and
manipulating relational databases.
Since a JDBC driver serves as the interface to
facilitate communications between JDBC and a
named database, JDBC drivers are database-specific.
Ch-3: JDBC Compiled by: Berhanu A. 5
Cont…
• IDBC is Industry standard for database-
independent connectivity between Java
applications and wide range of relational
databases (RDBMS)
• JDBC API split in to two.
– API: Set of interfaces independent of the RDBMS
– Driver: RDBMS-specific implementation of API
interfaces (e.g. Oracle, DB2, MySQL, etc.) which is
vendor specific.
• That means the JDBC API is uniform for any types
of database with its corresponding JDBC Driver.
Ch-3: JDBC Compiled by: Berhanu A. 6
JDBC Classes and Interfaces
Steps to using a database query:
• Load a JDBC “driver”
• Connect to the data source
• Send/execute SQL statements
• Process the results

Ch-3: JDBC Compiled by: Berhanu A. 7


JDBC Driver
• Acts as the gateway to a database
• Not actually a “driver”, just a .jar file
Java application Database Server

JDBC Driver

Ch-3: JDBC Compiled by: Berhanu A. 8


JDBC Driver Management
• All drivers are managed by the DriverManager class
• Example - loading an Oracle JDBC driver:
– In the Java code:
Class.forName(“oracle.jdbc.driver.OracleDriver”)
• Driver class names:
Oracle: oracle.jdbc.driver.OracleDriver
MySQL: com.mysql.jdbc.Driver
MS SQL Server:com.microsoft.jdbc.sqlserver.SQLServerDriver

Ch-3: JDBC Compiled by: Berhanu A. 9


Establishing a Connection
• Create a Connection object
• Use the DriverManager to grab a connection
with the getConnection method
• Necessary to follow exact connection syntax
• Problem 1: the parameter syntax for
getConnection varies between JDBC drivers
• Problem 2: one driver can have several
different legal syntaxes

Ch-3: JDBC Compiled by: Berhanu A. 10


Establishing a Connection (cont.)
MySQL Example
• Connection con =
DriverManager.getConnection(string);
• what to supply for string ?
• “jdbc:mysql://<URL>:3306/<DB>?user=<user>&password=<pw>”

Driver URL Port DB Username Password


Name

Ch-3: JDBC Compiled by: Berhanu A. 11


Executing Statements
• Obtain a statement object from the connection:
– Statement stmt = con.createStatement ();
• Execute the SQL statements:
– stmt.executeUpdate(“update table set field=‘value’”);
– stmt.executeUpdate(“INSERT INTO mytable VALUES (1,
‘name’)”);
– stmt.executeQuery(“SELECT * FROM mytable”);

Ch-3: JDBC Compiled by: Berhanu A. 12


Retrieving Data
• ResultSet rs =
stmt.executeQuery(“SELECT id,name
FROM employees where id = 1000”)
• Some methods used in ResultSet:
– next()
– getString()
– getInt()

Ch-3: JDBC Compiled by: Berhanu A. 13


Using the Results
while (rs.next())
{
float s = rs.getInt("id");
String n = rs.getString("name");
System.out.println(s + " " + n);
}

Ch-3: JDBC Compiled by: Berhanu A. 14


Connection Class Interface
• public boolean getReadOnly() and
void setReadOnly(boolean b)
Specifies whether transactions in this connection are
read-only
• public boolean isClosed()
Checks whether connection is still open.
• public boolean getAutoCommit() and
void setAutoCommit(boolean b)
If autocommit is set, then each SQL statement is
considered its own transaction. Otherwise, a
transaction is committed using commit(), or aborted
using rollback().

Ch-3: JDBC Compiled by: Berhanu A. 15


Executing SQL Statements
• Three different ways of executing SQL
statements:
– Statement (both static and dynamic SQL statements)
– PreparedStatement (semi-static SQL statements)
– CallableStatment (stored procedures)
PreparedStatement class:Precompiled,
parametrized SQL statements:
– Structure is fixed
– Values of parameters are determined at run-time

Ch-3: JDBC Compiled by: Berhanu A. 16


Executing SQL Statements (cont.)
String sql=“INSERT INTO Sailors VALUES(?,?,?,?)”;
PreparedStatment pstmt=con.prepareStatement(sql);
pstmt.clearParameters();
pstmt.setInt(1,sid);
pstmt.setString(2,sname);
pstmt.setInt(3, rating);
pstmt.setFloat(4,age);
// we know that no rows are returned, thus we use
executeUpdate()
int numRows = pstmt.executeUpdate();

Ch-3: JDBC Compiled by: Berhanu A. 17


ResultSets
• PreparedStatement.executeUpdate only returns the
number of affected records
• PreparedStatement.executeQuery returns data,
encapsulated in a ResultSet object (a cursor)

ResultSet rs=pstmt.executeQuery(sql);
// rs is now a cursor
While (rs.next()) {
// process the data
}
Ch-3: JDBC Compiled by: Berhanu A. 18
ResultSets (cont.)
A ResultSet is a very powerful cursor:
• previous(): moves one row back
• absolute(int num): moves to the row with the
specified number
• relative (int num): moves forward or backward
• first() and last()

Ch-3: JDBC Compiled by: Berhanu A. 19


Matching Java-SQL Data Types
SQL Type Java class ResultSet get method
BIT Boolean getBoolean()
CHAR String getString()
VARCHAR String getString()
DOUBLE Double getDouble()
FLOAT Double getDouble()
INTEGER Integer getInt()
REAL Double getFloat()
DATE java.sql.Date getDate()
TIME java.sql.Time getTime()
TIMESTAMP java.sql.TimeStamp getTimestamp()
Ch-3: JDBC Compiled by: Berhanu A. 20
JDBC: Exceptions and Warnings
• Most of java.sql can throw and SQLException if
an error occurs (use try/catch blocks to find
connection problems)
• SQLWarning is a subclass of EQLException; not
as severe (they are not thrown and their
existence has to be explicitly tested)

Ch-3: JDBC Compiled by: Berhanu A. 21


End Of
Chapter Three
23 Ch-3: JDBC Compiled by: Berhanu A.

You might also like