Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

JDBC

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 44

Chapter 3

Database Access with JDBC

1
Database
• A database is a system for storing structured
information .
It is organized and stored in away that allows its quick
and efficient retrieval.
• Information is broken into tables.
• Each table will have unique name in the database.

2
SQL
• Structured Query Language, pronounced S-Q-L, or
Sequel
• To access or write applications for database
systems, you need to use the Structured Query
Language (SQL).
• SQL is the universal language for accessing
relational database systems.
• Application programs may allow users to access
database without directly using SQL, but these
applications themselves must use SQL to access the
database
3
Basic SQL Queries
• Create Table
• Select Statement
• Insert statement
• Update Statement
• Delete Statement

4
Using SQL statements on a database
• Creating a table/relation
• Adding or removing an attribute/field
• Updating data/record
• Inserting/populating data
• Modifying
• Deleting
• Reading data/record

5
• Creating table - Syntax
CREATE TABLE table_name
(
column_name column_data_type,
column_name column_data_type,
column_name column_data_type
);
• Example:
CREATE TABLE Employee
( number INT NOT NULL,
payRate DOUBLE PRECISION NOT NULL,
first VARCHAR(255) ,
last VARCHAR(255)
);

6
• Adding an attribute/field – syntax
ALTER TABLE table_name
ADD column_name column_data_type;
• Example
ALTER TABLE Employee ADD sex char(1);
• Removing an attribute/field - syntax
ALTER TABLE table_name
DROP column_name;
Example
ALTER TABLE Employee DROP sex;
Inserting/populating data – syntax
INSERT INTO table_name VALUES (column1, column2, column3, ...);
Example
• INSERT INTO Employee VALUES (101, 20.00, ‘Rich’, ‘Raposa’);
• INSERT INTO Employee (number, first, last) VALUES (102, ‘Rich’, ‘Little’);

7
• Modifying data – syntax
UPDATE table_name
SET column_name = value, column_name = value, ...
WHERE conditions;
• Example
UPDATE Employee SET payRate=40.00 WHERE number=101;

• Deleting data – syntax


DELETE FROM table_name WHERE conditions;
• Example
DELETE FROM Employee WHERE number=101;

8
• Reading data – syntax
SELECT column_name, column_name, ...
FROM table_name
WHERE conditions;

• Example
• SELECT first, last, payRate FROM Employee WHERE number = 101;
• SELECT * FROM Employee WHERE number = 101;
• SELECT number FROM Employee WHERE last LIKE ‘R%’;
• SELECT * FROM Employees WHERE payRate > 10.0 AND payRate
<= 20.0;

9
Introduction of JDBC
• JDBC is a Java database connectivity API.
• Allows Java programs to contain database-independent code.
• Provides a mechanism for Java code to be portable across databases.
• Simplifies the creation and execution of SQL statements.
• Uses java.sql package.
• java.sql.DriverManager - Manages the loading and unloading of database
drivers from the underlying system.
• java.sql.Connection - Handles the connection to a specific database.
• java.sql.Statement - Contains an SQL statement to be passed to the database.
• java.sql.ResultSet - Contains the record result set from the SQL statement
passed to the database.
• To connect to a database and access its contents, JDBC driver that
works with that particular database is required.

10

JDBC consists of two parts:
 The JDBC API, a purely Java-based
API
JDBC Driver Manager, which
communicates with vendor-specific
drivers that interact with the database
 translation to vendor format is performed on
the client
 No changes needed to server
 Driver (translator) needed on client

11
Steps in Using JDBC
1. Load the JDBC driver
2. Define the Connection URL
3. Establish the Connection
4. Create a Statement object
5. Execute a query
6. Process the results
7. Close the connection

12
What are JDBC drivers?
JDBC drivers implement the defined interfaces in the JDBC API
for interacting with your database server.
For example, using JDBC drivers enable you to open database
connections and to interact with it by sending SQL or database
commands then receiving results with Java.
Database vendors and third parties can produce them.
Once you obtain a JDBC driver you should only have to worry
about registering it using DriverManager objects and creating
the proper JDBC URL in order to use it.

13
JDBC driver types
 JDBC driver implementations vary because of the wide variety of
operating systems and hardware platforms in which Java operates.
 Thus, Sun has divided the implementation types into four categories,
Types 1, 2, 3, and 4, whose characteristics vary greatly.
 Types 1 and 2 rely heavily on additional software (typically C/C++
DLLs) installed on the client computer to provide database connectivity.
Java and JDBC use these components to interact with the database.
 Types 3 and 4 are pure Java implementations and require no additional
software to be installed on the client, except for the JDBC driver.
Fortunately, packaging the JDBC driver with your software distribution
is trivial.

14
Type 1: JDBC−ODBC bridge
 This category works with ODBC drivers supplied by your database vendor or a third
party. To use the bridge, you must first have an ODBC driver specifically for your
database and any additional software that you need for connectivity.
 Using ODBC also requires configuring on your system a Data Source Name (DSN) that
represents the target database.
Cons
Pros  You must set up and maintain ODBC data
Can access local databases such as sources.
Microsoft Access and FoxPro.  Slow. The extra ODBC layer necessitates

Useful for testing basic JDBC features on additional processing.


 May require additional client software such
stand alone Windows computers.
as database network connectivity
components.
 Not usable when deployment requires
automatic downloading and configuration of
applications.

15
Type 2: JDBC−native API
 This category requires an operating system–specific API that handles the database
communications. Usually the vendor implements the API using C/C++ so it will be
optimized for the client’s environment.
 The Type 2 driver is like the Type 1 driver in that JDBC calls are converted by the native
API into the format recognized by the target database.
 Pros
 Faster than Type 1 because the ODBC layer is removed.
 Native code optimized for your platform and DBMS
 Cons
 A vendor−specific API must be installed on client computer.
 Not usable when deployment requires automatic downloading and configuration of
applications.

16
Type 3: 100% Pure Java, JDBC−network
 Type 3 drivers use a three−tier approach to accessing databases.
 J2EE deployments often implement this architecture. Clients use standard
network sockets to communicate with an application server. The socket
information is then translated by the application server into the call format
required by the DBMS, and forwarded to the database server.
Pros
 No additional client software required.
 Application server may give you access to multiple DBMSs.

Cons
 Middleware product or application server required.
 May require additional configuration for Internet use.

17
Type 4: 100% Java
 This driver is implemented entirely in Java and encapsulates the
database−specific network protocols to communicate directly with the
DBMS. As with the Type 3 driver, clients do not need additional software.
Because of the proprietary nature of their network protocols, database
vendors usually supply type 4 drivers.
Pros
 No additional client software required.
 Direct communication with database server.

Cons
May require additional configuration for Internet use.

18
Some Popular JDBC Drivers
RDBMS JDBC Driver Name
Driver Name
com.mysql.jdbc.Driver
MySQL
Database URL format:
jdbc:mysql://hostname/databaseName

Driver Name:
oracle.jdbc.driver.OracleDriver
Oracle
Database URL format:
jdbc:oracle:thin@hostname:portnumber:databaseName

Driver Name:
org.apache.derby.jdbc.ClientDriver
JavaDB
Database URL format:
jdbc:derby://localhost:1527/databaseName

Driver Name:
sun.jdbc.odbc.JdbcOdbcDriver
Access
Database URL format:
jdbc:odbc:databaseName

19
Registering JDBC drivers
To use your JDBC driver you must first register it with the
DriverManager object, which has a driver−registration method.
Moreover, there are techniques available for registering JDBC
drivers.
The following is a list of the three different ways to register a
JDBC driver:
Class.forName(String driverName)
DriverManager.registerDriver(Driver driverName)
jdbc.drivers property

20
Registering JDBC Driver
 Using Class.forName(String driverName).newInstance() is the most common way to
register a JDBC driver. Besides instantiating a new JDBC Driver object, it also allows the
object to register itself with DriverManager.
 The JDBC specification requires Driver objects to register themselves with
DriverManager via a static initializer that calls the DriverManager.registerDriver()
method.
 This mechanism allows for dynamic driver registration at runtime regardless of how you
register your driver.

String driver = "sun.jdbc.odbc.JdbcOdbcDriver";


try {
Class.forName(driver).newInstance();
} catch(ClassNotFoundException e) { //Thrown if the driver class is not found in classpath.
e.printStackTrace();
}

21
Registering JDBC Driver
 DriverManager provides the DriverManager.registerDriver(Driver
driverName) method for registering JDBC drivers.

try {
DriverManager.registerDriver (new
sun.jdbc.odbc.JdbcOdbcDriver());
}
catch(SQLException e) {
e.printStackTrace();
}

22
Working with Connection Objects
 In JDBC, an instantiated Connection object is a physical connection to the
database.
 The Driver.connect() method does the work of supplying you with a Connection
object.
 You can use the Driver object directly, but DriverManager wraps the call with its
getConnection() method.
 For a number of reasons, using DriverManager is the preferred way to
open database connections.
 To name one, if you have registered several drivers DriverManager will determine the
appropriate driver to connect with.
 In addition, the getConnection() method is overloaded to provide you with a variety
of ways to open connections.

23
Connection
• A Connection represents a session with a specific database.
• Within the context of a Connection, SQL statements are
executed and results are returned.
• Can have multiple connections to a database
– NB: Some drivers don’t support serialized connections
– Fortunately, most do (now)
• Also provides “metadata” -- information about the database,
tables, and fields
• Also methods to deal with transactions

24
Selected Methods In java.sql.Connection
Method Purpose
Returns a statement object that is used to
Statement createStatement() send SQL to the database.

Returns an object that can be used for sending


PreparedStatement preparedStatement(String sql)
parameterized SQL statements.

CallableStatement prepareCall(String sql) Returns an object that can be used for calling
stored procedures.
Gets an object that supplied database
DatabaseMetaData getMetaData()
configuration information.

boolean isClosed() Reports whether the database is currently


open or not.

void commit() Makes all changes permanent since previous


commit.rollback.
Undoes and discards all changes done since
void rollback() the previous commit/rollback.

25
Understanding JDBC URLs
JDBC requires a naming system so you can connect to your
database
Here is the general structure:
jdbc:<subprotocol>:<subname>
The value of <subprotocol> indicates which vendor−specific protocol to
use when connecting to the database.
The <subname> value indicates the data source, or database, you want to
connect with. Some servers may hold more than one database and use
logical names to represent each one. In general, the <subname> value is the
logical name of the database on your database server.

26
JDBC URLs
Each driver has its own subprotocol
Each subprotocol has its own syntax for the source
jdbc:odbc:DataSource
 e.g. jdbc:odbc:Student_DB

jdbc:oracle:thin:@host:port:database
 e.g. jdbc:oracle:thin:@localhost:1521:Student_DB
jdbc:derby://host:port/databaseName
 e.g. jdbc:derby://localhost:1527/Student_DB
jdbc:mysql://host/database
jdbc:mysql://localhost/Student_DB

27
Opening connections
 The three overloaded DriverManager.getConnection() methods:
 getConnection(String url)
 getConnection(String url, Properties prop)
 getConnection(String url, String user, String password)
 The second method takes an additional parameter, a Properties object, besides the String url.
 Use this method if you need to pass specific information to your database when connecting.
Just set the appropriate name−value pairs in the object and supply it as a parameter when you
call the method
 When you call the getConnection() method, DriverManager returns a valid Connection object.
 DriverManager begins with the first JDBC driver and tries to make a connection; if it fails,
DriverManager tries the next one. It repeats this process until it finds a driver that can connect to
the database described by your JDBC−URL

28
Opening connection
String url = "jdbc:oracle:thin:@myServer:1521:PROD";
String user = "boss";
String pwd = "bosspwd";
Connection conn = DriverManager.getConnection(url,user,pwd);
 Similarly, you can instantiate a Driver directly and use it to connect

Driver drv = com.mysql.jdbc.Driver();


Properties prop = new Properties();
Connection conn = drv.connect("jdbc:odbc:authors",prop);
 The prop variable is used to hold a set of parameters, such as user and password, that you
need in order to connect to your database. It is empty in this case.

29
Obtaining a Connection
String url = " com.mysql.jdbc.Driver ";
try {
Class.forName (" com.mysql.jdbc.Driver ");
Connection con = DriverManager.getConnection(url);
}
catch (ClassNotFoundException e)
{ e.printStackTrace(); }
catch (SQLException e)
{ e.printStackTrace(); }

30
Connection Methods
Statement createStatement()
 returns a new Statement object
PreparedStatement prepareStatement(String sql)
 returns a new PreparedStatement object

CallableStatement prepareCall(String sql)


 returns a new CallableStatement object

31
Using JDBC Statements
 The JDBC Statement, CallableStatement, and PreparedStatement
interfaces define the methods and properties that enable you to send
commands and receive data from your database.
They also define methods that help bridge data type differences between Java
and SQL data types used in a database.
 Statement is the parent, that PreparedStatement extends Statement, and
that CallableStatement extends PreparedStatement.
 Driver vendors provide classes that implement these interfaces. Without a
JDBC driver you cannot create objects based on these interfaces.

32
Using JDBC Statements
– Through the Statement objects, SQL statements are sent to the
database
– Three types of statement objects are available:
• Statement
– For executing a simple SQL statement
• PreparedStatement
– For executing a precompiled SQL statement passing in parameters
• CallableStatement
– For executing a database stored procedure

33
Introducing Statement Objects
The Statement object provides you with basic database−interaction
capabilities.
However, it still gives you significant capabilities. It enables you to
use all types of DML, DDL and other database specific commands.
In addition, it supports batch updating, which enables you to
implement transaction management.
You create the object from a valid Connection object, as shown in
the following example:
Connection conn = DriverManager.getConnection(url, "toddt", "mypwd");
Statement stmt = conn.createStatement();

34
Useful Statement Methods
• RessultSet executeQuery(String)
– Executes the SQL query and returns the data in a table (ResultSet)
– The resulting table may be empty but never null
ResultSet results = statement.executeQuery("SELECT a, b FROM table");
• int executeUpdate(String)
– Execute for INSERT, UPDATE, or DELETE statements
– Returns number of rows affected
– Supports Data Definition Language (DDL) statements CREATE TABLE,
DROP TABLE and ALTER TABLE
int rows = statement.executeUpdate("DELETE FROM EMPLOYEES
WHERE STATUS=0");

35
Useful Statement Methods(Cont’d)
• execute(String sql)
– Execution may or may not return a ResultSet (use statement.getResultSet). If
the return value is true, two or more result sets were produced
• getMaxRows/setMaxRows
– Maximum number of rows a ResultSet may contain
– Unless explicitly set, the number of rows is unlimited (return value of 0)
• getQueryTimeout/setQueryTimeout
– Specifies the amount of a time a driver will wait for a STATEMENT to
complete before throwing a SQLException

36
Prepared Statements
• If executing similar SQL multiple times, using “prepared”
(parameterized) statements may be more efficient
– Statement is created in standard form that is sent to the database for
compilation before actually being used
– Each time you use it, you simply replace some of the marked
parameters using the setXxx methods
• As PreparedStatement inherits from Statement, the corresponding
execute methods have no parameters
– execute(), executeQuery(), executeUpdate()

37
Prepared Statement Example
Connection con = DriverManager.getConnection(url, user, password);
PreparedStatement stmt = con.prepareStatement("UPDATE employees "+
"SET salary = ? " + "WHERE id = ?");
int[] newSalaries = getSalaries();
int[] employeeIDs = getIDs();
for(int i=0; i<employeeIDs.length; i++) {
stmt.setInt(1, newSalaries[i]);
stmt.setInt(2, employeeIDs[i]);
stmt.executeUpdate();
}

38
ResultSet
 Connection objects represent database connections; Statement objects
enable you to execute SQL statements against the database.
 The term “result set” refers to the row and column data contained in a
ResultSet object.
This is a logical view of row and column data in your database that meets the
criteria of your SQL query.
 A result set can have any number of rows and columns: the actual number
depends on the query.
If you place a WHERE clause in your SQL statement, only the row data
meeting those criteria will be retrieved.

39
Result set cursors
 Despite the number of rows in a result set, you can only access one row at
a time.
 A ResultSet object points to this "active" row using a cursor. If you want
to reference another row in the result set you must explicitly move the
cursor with one of the ResultSet object’s cursor-movement methods.
 Two cursor positions within a result set warrant special mention.
 These are the “before first row” (BFR) and “after last row” (ALR) cursor positions in
the result set.
 These areas are devoid of data and an SQLException occurs if you use the getXXX()
or updateXXX() methods in these locations.

40
Types of ResultSet
 Standard
 Enables basic access to the result set data. Does not reflect changes to underlying
data on server. Moves in one direction, forward. Data within the result set cannot be
updated.
 Scrollable
 Provides enhanced movement capabilities over the standard ResultSet object. Moves
forward, backward, or to any row. Can reflect data changes on the server. You set this
type with the resultSetType parameter when creating the Statement,
PreparedStatement, or CallableStatement object.
 Updateable
 Enables you to update underlying database information through the ResultSet object.
You set this type with the resultSetConcurrency parameter when creating the
Statement, PreparedStatement, or CallableStatement object.
 EX:
 Statement st=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.UPDATABLE)

 ResultSet s; 41
 S.absolute(5)….// go to the fifth row
Example:
import java.sql.*;
public class NorthwindTest {
public static void main(String[] args) {
String driver = " com.mysql.jdbc.Driver ";
String url = "  jdbc:mysql://localhost:3306/db_name ";
String username = "";
String password = "";
showEmployeeTable(driver, url, username, password);
}
public static void showEmployeeTable(String driver, String url, String username,
String password) {
try {
// Load database driver if not already loaded.
Class.forName(driver);
// Establish network connection to database.
Connection connection = DriverManager.getConnection(url,
username, password);

42
Example: (cont’d)
System.out.println("Employees\n" + "=========");
Statement statement = connection.createStatement();
String query = "SELECT firstname, lastname FROM employees";
// Send query to database and store results.
ResultSet resultSet = statement.executeQuery(query);
// Print results.
while(resultSet.next()) {
System.out.print(resultSet.getString(1) + " "); // First name
System.out.println(resultSet.getString(2)); // Last name
}
} catch(ClassNotFoundException cnfe) {
System.err.println("Error loading driver: " + cnfe);
} catch(SQLException sqle) {
System.err.println("Error connecting: " + sqle);
}
}
}

43
The End
44

You might also like