Documente Academic
Documente Profesional
Documente Cultură
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
Rows, columns
Unique data
Primary key
Introduction (3)
Primary key
Column
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
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 :
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.
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
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
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
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
Java to C
Java Appl.
JDBC Runtime
JDBCODBC Driver
DB specifics
ODBC Driver
ODBC APIs Initialization, Driver bindings
RDBMS
ODBC Interface
ODBC Runtime
15
JDBC (3)
16
JDBC (4)
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
18
19
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
DDL : data definition language. DML : data manipulation language. DCL(Transact-SQL): data control language.
21
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
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
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
Ex: String url= sun.jdbc.odbc.JdbcOdbcDriver; Class.forName(url); Ex: String dbURL= "jdbc:odbc:yourDataSource"; Ex: Connection conn = DriverManager.getConnection(dbURL);
25
2.
3.
26
27
Examples:
o
o
o
28
2.
Next, place the statement that you want to execute into a string :
String sqlCMD=;
3.
29
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
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
ResultSet object :
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
33
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
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:
36
37
Or:
38
To passing parameter in this case, we must use PrepareStatement objecct instead using Statement object.
39
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);
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
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);
42
43
44
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
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:
47
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
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
The deleteRow method immediately removes the row from both the result set and the database.
51
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:
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 a stored procedure with no parameters would look like this:
{call procedure_name}
55
CallableStatement (3)
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
59
CallableStatement (6)
Numbering of Parameters :
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:
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)
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)
66
Metadata (5)
Checking nullable
int nullable=rsmd.isNullable(i); return value: ParameterMetaData.parameterNoNulls, ParameterMetaData.parameterNullable, or ParameterMetaData.parameterNullableUnknown
Metadata (6)
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)
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);
Metadata (11)
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 (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.
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
JTable:
DefaultTableModel:
tbl.getTableHeader().setXXX();
92
JTable:
(cont.)
Add row :
Object obj[]=new Object[i]; dtm.addRow(obj); dtm. removeRow(i);
dtm.setRowCount(0);
Remove row:
Clear table:
93
JSplitPane
94
THE END.
95