Java_JDBC

Post on 24-Oct-2014

81 views 1 download

Tags:

transcript

Database Connectivitive

JDBC

Database Connectivitive

JDBC

2

Chapter’s Objectives1. Introduction2. The Design of JDBC3. The Structured Query Language4. Installing JDBC5. Basic JDBC Programming Concepts6. Executing Queries7. Scrollable and Updatable Result Sets8. Metadata9. Row Sets10. Transactions11. Advanced Connection Management

3

Part 1: Introduction

4

Introduction (1)

Database Collection of data

DBMS Database management system Stores and organizes data

SQL Relational database Structured Query Language

5

Introduction (2)

RDBMS Relational database management

system Relational database

Table Rows, columns

Primary key Unique data

6

Introduction (3)

Example: Employee table

Number Name Department Salary Location

23603 Jones 413 1100 New Jersey

24568 Kerwin 413 2000 New Jersey

34589 Larson 642 1800 Los Angeles

35761 Myers 611 1400 Orlando

47132 Neumann 413 9000 New Jersey

78321 Stephens 611 8500 Orlando

Row

ColumnPrimary key

7

ODBC overview (1)

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.

8

ODBC overview (2)

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

9

ODBC overview (3)

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.

10

ODBC overview (4)

Driver Manager: Loads drivers on an as-needed basis for

applications Maps a target database name to a

specific driver Processes several ODBC initialization

calls Validates the parameters and

sequences of ODBC calls

11

ODBC overview (5)

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.

12

ODBC overview (6)

Target-Database Middleware : Includes the database needed by the

applications and the associated middleware

Database may be located on the same machine or remote machine.

13

The Design of JDBC (1)

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.

14

JDBC (2)

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.

15

JavaAppl.

JDBCRuntime

JDBC-ODBCDriver

ODBCDriver

RDBMS

ODBCInterface

ODBCRuntime

Windows3G/4GAppl.

DBspecifics

Java to C

ODBC APIs

Initialization,Driver bindings

JDBC Objectsand interfaces

16

JDBC (3)

17

JDBC (4) 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.

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.

18

Typical Uses of JDBC (1)

19

Typical Uses of JDBC (2)

20

STRUCTURED QUERY LANGUAGE(1)

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.

21

STRUCTURED QUERY LANGUAGE(2)

There are 3 types of SQL language : DDL : data definition language. DML : data manipulation language. DCL(Transact-SQL): data control language.

22

Installing JDBC (1)

On Windows, it already include the JDBC/ODBC bridge driver.

We can use driver for Ms Access without installing any thing.

With MS SQL Server 2000, we must install the driver to use for accessing data.

23

Installing JDBC (2)

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.

24

Basic JDBC Programming Concepts (1)

Database URLs: When connecting to a database, you must

specify the data source and you may need to specify additional parameters.

Syntax: Jdbc:subprotocol name:other_stuff

subprotocol is used to select the specific driver for connecting to the database.

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.

Example : jdbc:odbc:your_Datasource

25

Basic JDBC Programming Concepts (2)

Making the Connection:1. Using url to specify the Driver manager:

Ex: String url=

“sun.jdbc.odbc.JdbcOdbcDriver”;

Class.forName(url);

2. Putting database URL: Ex: String dbURL=

"jdbc:odbc:yourDataSource";

3. Create Connection object: Ex: Connection conn =

DriverManager.getConnection(dbURL);

26

Basic JDBC Programming Concepts (3)

Connect to Microsoft AccessClass.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…

27

Connect to Microsoft SQLServer 2000

28

Examples:o myJDBC_Connect.classo access.javao testConnect_01.java

29

Basic JDBC Programming Concepts (4)

Executing SQL Commands :1. To execute a SQL command, you first

create a Statement object.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.execcuteXXX(sqlCMD);

30

Basic JDBC Programming Concepts (5)

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.

31

Basic JDBC Programming Concepts (6)

ResultSet object : Get a set of records after execute a sql

command.ResultSet rs =

statement.executeQuery(sql); Using getXXX() methods to get specify

values from ResultSetEx : 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.

32

Basic JDBC Programming Concepts (7)

ResultSet object : Traverse through ResulSet :

while(rs.next()){process(rs.getXX(“fieldName”));

} Each getXXX() method will make

reasonable type conversions when the type of the method doesn't match the type of the column.

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

33

Basic JDBC Programming Concepts (8)

34

Advanced SQL Types (JDBC 2) In addition to numbers, strings, and dates,

many databases can store large objects such as images or other data. In SQL, binary large objects are called BLOBs, and character large objects are called CLOBs.

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.

35

Advanced SQL Types (JDBC 2) 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.

36

Part 2:

Working with JDBC

37

Executing Queries (1)

Execute select sql statement :ResultSet rs=statement.executeQuery(sql);

Ex: String sql=“select * from tblStudent”;ResultSet rs=statement.executeQuery(sql);

Or:String sql=

“select * from tblStudent where studentID like ‘sv%’”;ResultSet rs=statement.executeQuery(sql);

38

Executing Queries (2)

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);Or:

String sql=“delete from tblClass where classID=‘CDTH5A’”;

int recNum=statement.executeUpdate(sql);Or:

String sql=“update tblClass set studentsNum=100 where classID=‘CDTH5A’”;

int recNum=statement.executeUpdate(sql);

39

Executing Queries (3)

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 PrepareStatement objecct instead using Statement object.

40

Example:

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

PreparedStatement QueryStat =

conn.prepareStatement(pSql); Before executing the prepared

statement, you must bind the host variables to actual values with a setXXX() method.

Ex: setString(1, ‘CDTH4C’); The position 1 denotes the first “?” and

so on.

Executing Queries (4)

41

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 queryResultSet rs = QueryStat.executeQuery();

Executing Queries (5)

42

Scrollable and Updatable Result Sets (1)Scrollable Result Sets :

To obtain scrolling result sets from your queries, you must obtain a different Statement object with the method:Statement stat =

conn.createStatement(rs_type, concurrency);

For a prepared statement, use the callPreparedStatement stat =

conn.prepareStatement(command, rs_type,

concurrency);

43

Scrollable and Updatable Result Sets (2)

ResultSet type values :

44

Scrollable and Updatable Result Sets (3)

ResultSet concurrency values

45

Scrollable and Updatable Result Sets (4)

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_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

ResultSet rs = stat.executeQuery(query)

46

Scrollable and Updatable Result Sets (5) 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. rs.afterLast();// after the last position.

47

Scrollable and Updatable Result Sets (6)

Test whether the cursor is at one of these special positions: rs.isFirst(); rs.isLast(); rs.isBeforeFirst(); rs.isAfterLast();

48

Scrollable and Updatable Result Sets (7) 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.

49

Scrollable and Updatable Result Sets (8) To obtain updatable result sets, you

create a statement as follows.Statement stat =

conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_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”);rs.updateRow();

50

Scrollable and Updatable Result Sets (9)

Insert new row to ResultSet:1. rs.moveToInsertRow(); //create new insert row2. Call rs.updateXXX(“fieldName”,value)

methods.3. Call rs.insertRow() ;//actual insert row4. Call rs.moveToCurrentRow();//move to

previous row.

51

Scrollable and Updatable Result Sets (10)

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.

52

Scrollable and Updatable Result Sets (11)

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.

53

part 3:

Advanced JDBC programming

54

CallableStatement (1)

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).

55

CallableStatement (2)

The syntax for invoking a stored procedure in JDBC is shown here.{call procedure_name[(?, ?, ...)]}

The syntax for a procedure that returns a result parameter is:{? = call procedure_name[(?, ?, ...)]}

The syntax for a stored procedure with no parameters would look like this: {call procedure_name}

56

CallableStatement (3)

Creating a CallableStatement Object : CallableStatement objects are created with the

Connection method prepareCall :CallableStatement cstmt = con.prepareCall("{call procedureName(?, ?)}");Note: The “?” placeholders are IN, OUT, or INOUT parameters depends on the stored procedure procedureName.

57

CallableStatement (4)

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");

View sample : callStatement_01.java

58

CallableStatement (5)

OUT Parameters : If the stored procedure returns OUT

parameters, the JDBC type of each OUT parameter must be registered before the CallableStatement object can be executed

Registering the JDBC type is done with the method registerOutParameter. Then after the statement has been executed, CallableStatement's getXXX methods can be used to retrieve OUT parameter values.

59

Ex:CallableStatement cstmt = con.prepareCall(

"{call getTestData(?, ?)}"); cstmt.registerOutParameter(1,

java.sql.Types.TINYINT);cstmt.registerOutParameter(2,

java.sql.Types.DECIMAL, 3);ResultSet rs = cstmt.executeQuery(); // . . . retrieve result set values with rs.getXXX methods

byte x = cstmt.getByte(1); java.math.BigDecimal n =

cstmt.getBigDecimal(2, 3);View Sample : --Eclipse project--

60

CallableStatement (6)

Numbering of Parameters : CallableStatement cstmt =

con.prepareCall("{call getTestData(25, ?)}"); cstmt.registerOutParameter(1,

java.sql.Types.TINYINT);

61

CallableStatement (7)

INOUT Parameters : A parameter that supplies input as well

as accepts output (an INOUT parameter) requires a call to the appropriate setXXX method (inherited from 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.

62

CallableStatement cstmt = con.prepareCall( "{call reviseTotal(?)}");

cstmt.setByte(1, 25); cstmt.registerOutParameter(1,

java.sql.Types.TINYINT); cstmt.execute(); byte x = cstmt.getByte(1);

63

Metadata (1)

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

64

Metadata (2)

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.

65

Metadata (3)

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"); ResultSetMetaData rsmd = rs.getMetaData() ;

66

Metadata (4)

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);}

View sample getColumnName.java

67

Metadata (5)

Get Table NameString tableName=rsmd.getTableName(i);

Get Column data typeint jdbcType=rsmd.getColumnType(i);

String DBMSname = rsmd.getColumnTypeName(i);

Checking nullableint nullable=rsmd.isNullable(i);

return value:

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

View sample :getColumnType.java

68

Metadata (6)

Getting Information about a Database or Database System : Once you have an open connection with

a DBMS, you can create a DatabaseMetaData object that contains information about that database system. Using the Connection object con, the following line of code creates the DatabaseMetaData object dbmd:DatabaseMetaData dbmd =

con.getMetaData();

69

Metadata (7)

Methods:ResultSet rs=dbmd.getTables(String

catalog, String schemaPattern, String tableNamePattern, String types[]);

Gets a description of all tables in a catalog that match the schema and table name patterns and the type criteria.

A Schema describes a groups of related table and access permissions. A Catalog describes a related groups of schemas.

70

Metadata (8)

Ex: page 241. String[]tblType={“TABLE”}; ResultSet

rs=dbmd.getTables(null,null,null,tblType); The types array contains the names of the

table types to include. Typical types are TABLE, VIEW, SYSTEM TABLE, GLOBAL TEMPORARY, LOCAL TEMPORARY, ALIAS, and SYNONYM. If types is null, then tables of all types are returned.

View sample : getAllDBTable.java

71

Methods:getColumns(String catalog, String schemaPattern,

String tableNamePattern,

String columnNamePattern);

Retrieves a description of table columns available in the specified catalog.

Ex:ResultSet columnName=metadata.getColumns

(null,null,tableName,null);

View sample: getTableInfos.java

Metadata (9)

72

Metadata (11)

Design sample application:1. Retrieve all table in database.2. For each table in database, gets all

informations.3. Display result using GUI.View sample :metaDataDEMO.jar

73

Metadata (11) Another way to retrieve metadata

o We can use sql command to retrieve infos from metadata.

o Example, in SQL Server, we can use system table (sysObjects, sysTables, sysColumns,…) and support procedures (sp_help, sp_table,…) to get all infos about catalog, schema, database, table and so on).

o View sample : getMetaData.java

74

75

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

76

CachedRowSet (1)

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.

77

CachedRowSet (2)

You can modify the data in a cached row set.

The modifications are not immediately reflected in the database.

You need to make an explicit request to accept the accumulated changes.

The CachedRowSet reconnects to the database and issues SQL commands to write the accumulated changes.

78

CachedRowSet (3)

Cached row sets are not appropriate for large query results.

You can populate a CachedRowSet from a result set:

79

CachedRowSet (4)

You can let the CachedRowSet object establish a connection automatically. Set up the database parameters:

rowset.setURL(myURL);

rowset.setUsername("username");

rowset.setPassword(“myPSW");

80

CachedRowSet (5)

If you modified the row set contents, you must write it back to the database by callingrowset.acceptChanges(conn);

orrowset.acceptChanges();

81

CachedRowSet (6)

A row set that contains the result of a complex query will not be able to write back changes to the database.

You should be safe if your row set contains data from a single table.

82

CachedRowSet (7)

Using a cached row set, the program logic is now greatly simplified.o We simply open and close the

connection in every action listener.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.

83

Other rowsets A WebRowSet is a cached row set that can

be saved to an XML file. The XML file can be moved to another tier of a web application, where it is opened by another WebRowSet object.

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."

84

85

Transaction (1)

The major reason for grouping commands into transactions is database integrity.

If you group updates to a transaction, then the transaction either succeeds in its entirety and it can be committed, or it fails somewhere in the middle. In that case, you can carry out a rollback and the database automatically undoes the effect of all updates that occurred since the last committed transaction.

86

Transaction (2)

By default, a database connection is in autocommit mode, and each SQL command is committed to the database as soon as it is executed. Once a command is committed, you cannot roll it back.

To check the current autocommit mode setting, call the getAutoCommit() method of the Connection class.

87

Transaction (3) Implementing transaction:

1. You turn off autocommit mode with the command: conn.setAutoCommit(false);

2. Now you create a statement object in the normal way: Statement stat =

conn.createStatement();

3. Call executeUpdate any number of times.

4. When all commands have been executed, call the commit method:

conn.commit();

5. However, if an error occurred, call conn.rollback();

88

Transaction (4)

Batch Updates : Use the supportsBatchUpdates method of

the DatabaseMetaData class to find out if your database supports this feature.

The commands in a batch can be actions such as INSERT, UPDATE, and DELETE as well as data definition commands such as CREATE TABLE and DROP TABLE.

However, you cannot add SELECT commands to a batch since executing a SELECT statement returns a result set.

89

Transaction (5)

1. To execute a batch, you first create a Statement object in the usual way: Statement statment = conn.createStatement();

2. Now, instead of calling executeUpdate, you call the addBatch method:String sqlCommand = ". . ."statement.addBatch(sqlCommand);

3. Finally, you submit the entire batch:int[] counts = stat.executeBatch();

90

Transaction (6)

For proper error handling in batch mode, you want to treat the batch execution as a single transaction. If a batch fails in the middle, you want to roll back to the state before the beginning of the batch.

First, turn autocommit mode off, then collect the batch, execute it, commit it, and finally restore the original autocommit mode.

See example as follow:

91

Transaction (7)try{

boolean autoCommit = conn.getAutoCommit();

conn.setAutoCommit(false);Statement stat = conn.getStatement();. . .// keep calling stat.addBatch(. . .);. . .stat.executeBatch();conn.commit();conn.setAutoCommit(autoCommit);

}catch(SQLException sqlEx){conn.rollback();

}

92

Advanced Swing components(1)

JTable: DefaultTableModel:

DefaultTableModel dtm=new DefaultTableModel(title,numRows);

String[]Title={“”,””,…}; JTable tbl=new JTable(dtm); Set table header

tbl.getTableHeader().setXXX(…);

93

Advanced Swing components(2)

JTable: (cont.) Add row :

Object obj[]=new Object[i]; dtm.addRow(obj);

Remove row: dtm. removeRow(i);

Clear table: dtm.setRowCount(0);

94

Advanced Swing components(1)

JSplitPane JSplitPane(int Direction,Componet first,

Component seconds); Direction :HORIZONTAL_SPLIT or

VERTICAL_SPLIT

95

THE END.