Sunteți pe pagina 1din 95

Database Connectivitive JDBC

Chapters Objectives
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.

Introduction The Design of JDBC The Structured Query Language Installing JDBC Basic JDBC Programming Concepts Executing Queries Scrollable and Updatable Result Sets Metadata Row Sets Transactions Advanced Connection Management
2

Part 1:

Introduction

Introduction (1)

Database

Collection of data Database management system Stores and organizes data Relational database Structured Query Language

DBMS

SQL

Introduction (2)

RDBMS

Relational database management system Table

Relational database

Rows, columns
Unique data

Primary key

Introduction (3)

Example: Employee table


Number 23603 24568 Row 34589 35761 47132 78321 Name Jones Kerwin Larson Myers Neumann Stephens Department 413 413 642 611 413 611 Salary 1100 2000 1800 1400 9000 8500 Location New Jersey New Jersey Los Angeles Orlando New Jersey Orlando

Primary key

Column

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

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

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.

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

10

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.

11

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.

12

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

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.

14

JDBC Objects and interfaces

Java to C

Java Appl.

JDBC Runtime

JDBCODBC Driver

DB specifics

ODBC Driver
ODBC APIs Initialization, Driver bindings

RDBMS

Windows 3G/4G Appl.

ODBC Interface

ODBC Runtime

15

JDBC (3)

16

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 platformspecific 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.
17

Typical Uses of JDBC (1)

18

Typical Uses of JDBC (2)

19

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.

20

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.

21

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.

22

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.

23

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

24

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); Ex: String dbURL= "jdbc:odbc:yourDataSource"; Ex: Connection conn = DriverManager.getConnection(dbURL);
25

2.

Putting database URL:

3.

Create Connection object:

Basic JDBC Programming Concepts (3)

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

26

Connect to Microsoft SQLServer 2000

27

Examples:
o

o
o

myJDBC_Connect.class access.java testConnect_01.java

28

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

29

Basic JDBC Programming Concepts (5)

Execute methods of Statement object:


1.

2. 3. 4.

ExecuteUpdate() : exec a non return value query (delete,insert,updatequeries). executeQuery() : Execute and return a set of records. executeBatch() : execute a batch of commands. Execute() : multipurpose command to execute any types of SQL command.
30

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

31

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:
32

Basic JDBC Programming Concepts (8)

33

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.

34

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 userdefined structured types. JDBC 2 supports a mechanism for automatically mapping structured SQL types to Java objects.

35

Part 2:

Working with JDBC

36

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

37

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,Nguyn Vn Bnh,cntt); int recNum=statement.executeUpdate(sql); 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);

Or:

38

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.

39

Executing Queries (4)


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.


40

Executing Queries (5)

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

41

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 call


PreparedStatement stat = conn.prepareStatement(command, rs_type, concurrency);

42

Scrollable and Updatable Result Sets (2) ResultSet type values :

43

Scrollable and Updatable Result Sets (3) ResultSet concurrency values

44

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)

45

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

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

47

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.

48

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();
49

Scrollable and Updatable Result Sets (9) Insert new row to ResultSet:
1. 2.
3.

4.

rs.moveToInsertRow(); //create new insert row Call rs.updateXXX(fieldName,value) methods. Call rs.insertRow() ;//actual insert row Call rs.moveToCurrentRow();//move to previous row.

50

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.

51

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.

52

part 3:

Advanced JDBC programming

53

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

54

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}
55

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.

56

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
57

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.

58

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

59

CallableStatement (6)

Numbering of Parameters :

CallableStatement cstmt = con.prepareCall("{call getTestData(25, ?)}"); cstmt.registerOutParameter(1, java.sql.Types.TINYINT);

60

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

CallableStatement cstmt = con.prepareCall( "{call reviseTotal(?)}"); cstmt.setByte(1, 25); cstmt.registerOutParameter(1, java.sql.Types.TINYINT); cstmt.execute(); byte x = cstmt.getByte(1);

62

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


63

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.

64

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

65

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

66

Metadata (5)

Get Table Name


String tableName=rsmd.getTableName(i);

Get Column data type


int jdbcType=rsmd.getColumnType(i); String DBMSname = rsmd.getColumnTypeName(i);

Checking nullable
int nullable=rsmd.isNullable(i); return value: ParameterMetaData.parameterNoNulls, ParameterMetaData.parameterNullable, or ParameterMetaData.parameterNullableUnknown

View sample :getColumnType.java


67

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();
68

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

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

70

Metadata (9)
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


71

Metadata (11)

Design sample application:


Retrieve all table in database. 2. For each table in database, gets all informations. 3. Display result using GUI. View sample :metaDataDEMO.jar
1.

72

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

73

74

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 o o o

CachedRowSet WebRowSet FilteredRowSet and JoinRowSet JdbcRowSet


75

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

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.

77

CachedRowSet (3)

Cached row sets are not appropriate for large query results. You can populate a CachedRowSet from a result set:

78

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

79

CachedRowSet (5)

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

80

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.

81

CachedRowSet (7)

Using a cached row set, the program logic is now greatly simplified.
o
o o

We simply open and close the connection in every action listener. We no longer need to trap the "window closing" event to close the connection. We no longer worry whether the result set is scrollable. Row sets are always scrollable.

82

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

84

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.

85

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

Transaction (3)

Implementing transaction:
1.

2.

You turn off autocommit mode with the command: conn.setAutoCommit(false); Now you create a statement object in the normal way: Statement stat = conn.createStatement(); Call executeUpdate any number of times. When all commands have been executed, call the commit method: conn.commit(); However, if an error occurred, call conn.rollback();
87

3. 4.

5.

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.

88

Transaction (5)
1.

2.

To execute a batch, you first create a Statement object in the usual way: Statement statment = conn.createStatement(); 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();
89

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:

90

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

}
91

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

92

Advanced Swing components(2)

JTable:

(cont.)

Add row :
Object obj[]=new Object[i]; dtm.addRow(obj); dtm. removeRow(i);
dtm.setRowCount(0);

Remove row:

Clear table:

93

Advanced Swing components(1)

JSplitPane

JSplitPane(int Direction,Componet first, Component seconds);

Direction :HORIZONTAL_SPLIT or VERTICAL_SPLIT

94

THE END.
95

S-ar putea să vă placă și