1. Trang chủ
  2. » Giáo án - Bài giảng

Chương 3 Database Programming JDBC

90 331 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Chương 3 Database Programming JDBC
Trường học University of Technology and Education
Chuyên ngành Database Programming
Thể loại Lecture Notes
Năm xuất bản 2023
Thành phố Hà Nội
Định dạng
Số trang 90
Dung lượng 267 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

The design of JDBC JDBC is a Java-based counterpart to ODBC  JDBC provides a standard API for tool/database developers and makes it possible to write database applications using a pu

Trang 1

Môn Lập trình Java NC

Chương 3: Database Programming JDBC

Trang 3

0 Introduction

Database

 Collection of data

DBMS

 Database management system

 Stores and organizes data

SQL

 Relational database

 Structured Query Language

Trang 5

0 Introduction (cont.)

ODBC overview

ODBC is an API introduced by Microsoft that allows

applications to access databases by using SQL

By using ODBC, a single application can access remote databases under different DBMSs (i.e Informix, Oracle, Sybase)

ODBC relies on data drivers to convert the ODBC calls to different database formats.

Trang 6

0 Introduction (cont.)

ODBC overview (cont.)

At development time, the application developer only needs

to know the ODBC calls to connect to a database, execute SQL statements, and retrieve results.

Main Components of ODBC:

 Application

 Driver manager

 Driver

 Target-database middleware

Trang 7

0 Introduction (cont.)

ODBC overview (cont.)

Application :

 Requests a connection with a target database

 Passes one or more SQL statements

 Processes the produced results or error conditions

 Ends each transaction with a commit or rollback

 Terminates the connection.

Trang 8

 Maps a target database name to a specific driver

 Processes several ODBC initialization calls

 Validates the parameters and sequences of ODBC calls

Trang 9

0 Introduction (cont.)

ODBC overview (cont.)

Driver :

 Processes the ODBC function calls

 Modifies them to the target database format

 Submits the SQL statements to the target database, receives the results, and presents the results to the application.

Trang 11

1 The design of JDBC

JDBC is a Java-based counterpart to ODBC

JDBC provides a standard API for tool/database

developers and makes it possible to write database

applications using a pure Java API.

Database developers will supply JDBC drivers for their databases so that Java programs may access them

transparently.

Trang 12

1 The design of JDBC (cont.)

ODBC is not appropriate for direct use from Java because

it uses a C interface (security, implementation,

robustness, portability)

A literal translation of the ODBC C API into a Java API

would not be desirable (void pointers)

JDBC is easier to learn.

A Java API like JDBC is needed in order to enable a “pure java” solution.

Trang 13

1 The design of JDBC (cont.)

Java Appl.

JDBC Runtime

ODBC Driver

JDBC-ODBC

ODBC Interface

ODBC Runtime

Windows 3G/4G Appl.

DB specifics Java to C

ODBC APIs

Initialization, Driver bindings JDBC Objects

and interfaces

Trang 14

1 The design of JDBC (cont.)

Trang 15

1 The design of JDBC (cont.)

JDBC drivers are classified into the following types:

type 1 driver translates JDBC to ODBC and relies

on an ODBC driver to communicate with the

database.

type 2 driver is a driver, written partly in the Java programming language and partly in native code, that communicates with the client API of a

database When you use such a driver, you must install some platform-specific code in addition to a Java library

Trang 16

1 The design of JDBC (cont.)

type 3 driver is a pure Java client library that uses a database-independent protocol to communicate

database requests to a server component, which

then translates the requests into a database-specific protocol The client library is independent of the

actual database, thus simplifying deployment.

type 4 driver is a pure Java library that translates

JDBC requests directly to a database-specific

protocol.

Trang 17

1 The design of JDBC (cont.)

Trang 18

2 The Structured Query Language

JDBC is an interface to SQL, which is the interface to

essentially all modern relational databases.

You can think of a database as a bunch of named tables with rows and columns Each column has a column name The rows contain the actual data These are sometimes

called records.

Trang 19

2 The Structured Query Language (cont.)

There are 3 types of SQL language :

 DDL : data definition language.

 DML : data manipulation language.

 DCL(Transact-SQL): data control language.

Trang 21

3 Installing JDBC (cont.)

To configure ODBC data source, follow these steps:

 Open windows Administrative tools

 Open “Data Sources (ODBC)”.

 Add new Data source.

 Select Driver : Microsoft Access Driver(*.mdb).

 Enter data source name.

 Select your database from specifie folder.

 Press OK to finish.

Trang 23

The format for the other stuff parameter depends

on the subprotocol used You need to look up your vendor's documentation for the specific format.

Trang 24

4 Basic JDBC programming concepts (cont.)

Making the Connection:

1 Using url to specify the Driver manager:

String url=

“sun.jdbc.odbc.JdbcOdbcDriver”;

Class.forName(url);

2 Putting database URL:

String dbURL= "jdbc:odbc:yourDataSource";

3 Create Connection object:

Connection conn = DriverManager.getConnection(dbURL);

Trang 25

4 Basic JDBC programming

concepts (cont.)

Connect to Microsoft Access

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

String database = "jdbc:odbc:Driver=

{Microsoft Access Driver (*.mdb)};DBQ=yourDB.mdb"; Connection conn =

DriverManager.getConnection( database,"Admin","" );

//do something after connect…

Trang 26

4 Basic JDBC programming concepts (cont.)

Connect to Microsoft SQLServer 2000

Trang 27

Statement statement = conn.createStatement();

2. Next, place the statement that you want to execute into a string :

String sqlCMD=“…”;

3. Then you call the executeXXX method.

statement.executeXXX(sqlCMD);

Trang 28

4 Basic JDBC programming

concepts (cont.)

Execute methods of Statement object:

1. executeUpdate(…) : exec a non return value query (delete,insert,update…queries).

2. executeQuery(…) : Execute and return a set of

records.

3. executeBatch() : execute a batch of commands.

4. execute(…) : multipurpose command to execute any types of SQL command.

Trang 29

Ex : String id=rs getString(“StudentID”);

 Parameters in getXXX() methods can be a

database field name or the index of DB field

Database column numbers start at 1.

Trang 30

 SQL data types and Java data types are not exactly the same See below:

Trang 31

4 Basic JDBC programming concepts (cont.)

Trang 32

The getBlob and getClob methods return objects of type

BLOB and CLOB These classes have methods to fetch the bytes or characters in the large objects.

Trang 33

4 Basic JDBC programming

concepts (cont.)

Advanced SQL Types

When you get a BLOB or an array from a database, the

actual contents are only fetched from the database when you request individual values This is a useful performance enhancement, since the data can be quite voluminous.

Some databases are able to store user-defined structured types JDBC 2 supports a mechanism for automatically

mapping structured SQL types to Java objects.

Trang 35

5 Executing Queries (cont.)

Execute insert,update, delete sql statement

int recNum=statement.executeUpdate(sql);

Ex:

String sql = “insert into tblClass values( ‘CDTH5A’,

’Cao dang TH 5A’,120,’Nguyễn Văn Bình’,’cntt’)”;

int recNum = statement.executeUpdate(sql);

Trang 36

5 Executing Queries (cont.)

Execute sql statement with parameters

Using parameters in your sql statement likes sample follow :

String pSql=“select * from tblClass where classID=?”

To passing parameter in this case, we must use

PreparedStatement objecct instead using Statement

object.

Trang 37

5 Executing Queries (cont.)

Trang 38

5 Executing Queries (cont.)

If you reuse a prepared query that you have already

executed and the query has more than one host variable, all host variables stay bound as you set them unless you change them with a set method

Once all variables have been bound to values, you can execute the query

ResultSet rs = QueryStat.executeQuery();

Trang 39

6 Scrollable and Updatable

ResultSet

Scrollable Result Sets :

 To obtain scrolling result sets from your queries, you must obtain a different Statement object with the

concurrency);

Trang 40

6 Scrollable and Updatable

ResultSet (cont.)

ResultSet type values :

Trang 41

6 Scrollable and Updatable

ResultSet (cont.)

ResultSet concurrency values

Trang 42

6 Scrollable and Updatable

ResultSet (cont.)

For example, if you simply want to be able to scroll

through a result set but you don't want to edit its data, you use:

Statement stat =

conn.createStatement( ResultSet.TYPE_SCROLL_I NSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stat.executeQuery(query)

Trang 43

6 Scrollable and Updatable

ResultSet (cont.)

After create the scrollable ResultSet, we can scrolling is very simple:

 rs.next(); //move next record.

 rs.previous(); //move previous record.

 rs.relative( n ); //move the cursor over n record(s).

 rs.first(); //move to first record.

 rs.last(); //move to last record.

 rs.absolute( n ); //set the cursor to a row nth.

 int n = rs.getRow();// gets the number of the current

//row Rows are numbered starting with 1.

 rs.beforeFirst();// before the first position.

Trang 44

6 Scrollable and Updatable

Trang 45

6 Scrollable and Updatable

ResultSet (cont.)

Updatable Result Sets :

 If you want to be able to edit result set data and have the changes automatically reflected in the database, you need to create an updatable result set

 Updatable result sets don't have to be scrollable, but if you present data to a user for editing, you usually want to allow scrolling as well.

Trang 46

6 Scrollable and Updatable

Then, the result sets returned by a call to executeQuery are updatable You can use updateXXX() methods of ResultSet

to update specify field.

Ex: rs.updateString(“className", “your enter class

Name”);

Trang 47

6 Scrollable and Updatable

ResultSet (cont.)

Insert new row to ResultSet:

1. rs.moveToInsertRow(); //create new insert row

2. Call rs.updateXXX(“fieldName”,value) methods.

3. Call rs.insertRow() ;//actual insert row

4. Call rs.moveToCurrentRow(); //move to previous

row.

You can delete the row under the cursor:

rs.deleteRow();

The deleteRow method immediately removes the row

from both the result set and the database.

Trang 48

6 Scrollable and Updatable

ResultSet (cont.)

The updateRow, insertRow, and deleteRow methods of the ResultSet class give you the same power as executing

UPDATE, INSERT, and DELETE SQL commands.

If you are not careful, you can write staggeringly inefficient code with updatable result sets It is much more efficient to execute an UPDATE statement than it is to make a query

and iterate through the result, changing data along the

way

Trang 49

* Advanced JDBC programming

CallableStatement

A CallableStatement object provides a way to call stored

procedures in a standard way for all RDBMSs

This call is written in an escape syntax that may take one

of two forms:

 One form with a result parameter.

 And the other without one

Both forms may have a variable number of parameters

used for input (IN parameters), output (OUT parameters), or both (INOUT parameters)

Trang 50

The syntax for a stored procedure with no parameters

would look like this:

{call procedure_name}

Trang 51

* Advanced JDBC programming

CallableStatement (cont.)

Creating a CallableStatement Object :

 CallableStatement objects are created with the

Connection method prepareCall :

CallableStatement cstmt =

con.prepareCall("{call procedureName(?, ?)}");

parameters depends on the stored procedure

Trang 52

* Advanced JDBC programming

CallableStatement (cont.)

IN Parameters :

 Passing in any IN parameter values to a

CallableStatement object is done using the setXXX methods inherited from PreparedStatement The

type of the value being passed in determines which setXXX method to use For example:

CallableStatement cs=con.prepareCall ("{call qClass_Dept(?)}");

cs.setString(1 ,“ cntt ");

Trang 53

methods can be used to retrieve OUT parameter

Trang 55

* Advanced JDBC programming

CallableStatement (cont.)

Numbering of Parameters :

 CallableStatement cstmt = con.prepareCall("{call getTestData(25, ?)}");

 cstmt.registerOutParameter(1,

java.sql.Types.TINYINT);

Trang 56

PreparedStatement) in addition to a call to the

method registerOutParameter The setXXX method sets a parameter's value as an input parameter, and the method registerOutParameter registers its

JDBC type as an output parameter.

Trang 58

* Advanced JDBC programming

Row Sets

The RowSet interface extends the ResultSet interface, but row sets don't have to be tied to a database connection.

The javax.sql.rowset package provides the following

interfaces that extend the RowSet interface:

o CachedRowSet

o WebRowSet

o FilteredRowSet and JoinRowSet

o JdbcRowSet

Trang 59

* Advanced JDBC programming

CachedRowSet

A CachedRowSet allows disconnected operation.

A cached row set contains all data from a result set

You can close the connection and still use the row set

Each user command simply opens the database

connection, issues a query, puts the result in a row set, and then closes the database connection

Trang 60

* Advanced JDBC programming

CachedRowSet (cont.)

Trang 62

* Advanced JDBC programming

CachedRowSet (cont.)

You can let the CachedRowSet object establish a

connection automatically Set up the database parameters: rowset.setURL(myURL); rowset.setUsername("username"); rowset.setPassword(“myPSW");

Trang 63

* Advanced JDBC programming

CachedRowSet (cont.)

If you modified the row set contents, you must write it back

to the database by calling

rowset.acceptChanges(conn);

or rowset.acceptChanges();

Trang 65

o We no longer need to trap the "window closing"

event to close the connection.

o We no longer worry whether the result set is

scrollable Row sets are always scrollable.

Trang 66

The FilteredRowSet and JoinRowSet interfaces support

lightweight operations on row sets that are equivalent to SQL SELECT and JOIN operations These operations are carried out on the data stored in row sets, without having

to make a database connection.

A JdbcRowSet is a thin wrapper around a ResultSet It

adds useful getters and setters from the RowSet interface, turning a result set into a "bean."

Trang 67

7 Metadata

JDBC can give you additional information about the

structure of a database and its tables For example, you can get a list of the tables in a particular database or the column names and types of a table.

Objective:

 Understand about database metadata.

 Using JDBC to get these informations

Trang 68

7 Metadata (cont.)

In SQL, data that describes the database or one of its parts

is called metadata (to distinguish it from the actual data

that is stored in the database) You can get two kinds of

metadata: about a database and about a result set.

The details of its will be descript as follow.

Trang 69

7 Metadata (cont.)

Getting Information about a Result Set :

 When you send a SELECT statement using JDBC, you get back a ResultSet object containing the data that satisfied your criteria You can get information about this ResultSet object by creating a

ResultSetMetaData object and invoking

ResultSetMetaData methods on it Ex:

Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery("select * from tblClass");

Trang 70

7 Metadata (cont.)

Gets count of columns in ResultSet:

int numCols = rsmd.getColumnCount();

Gets list of column name:

String []colNames=new String[numCols]; for (int i = 0; i<numCols; i++){

colNames [i]=rsmd.getColumnName(i+1); }

Trang 71

Checking nullable

int nullable=rsmd.isNullable( i );

return value:

ParameterMetaData.parameterNoNulls, ParameterMetaData.parameterNullable, or ParameterMetaData.parameterNullableUnknown

Ngày đăng: 13/05/2014, 11:01

TỪ KHÓA LIÊN QUAN

w