Академический Документы
Профессиональный Документы
Культура Документы
Database Programming
What is JDBC?
JDBC is: Java Database Connectivity
is a Java API for connecting programs written in Java to the data in relational databases. consists of a set of classes and interfaces written in the Java programming language. is used for accessing databases from Java applications.
JDBC:
establishes a connection with a database sends SQL statements processes the results sends back the results.
JDBC Architecture
Application JDBC Driver
Java code calls JDBC library JDBC loads a driver Driver talks to a particular database Can have more than one driver -> more than one database Ideal: can change database engines without changing any application code
JDBC is used by Java programmers to connect to databases With a small "bridge" program, you can use the JDBC interface to access ODBC-accessible databases.
JDBC API
The JDBC API supports both two-tier and three-tier models for database access. Two-tier model -- a Java applet or application interacts directly with the database. Three-tier model -- introduces a middle-level server for execution of business logic: the middle tier to maintain control over data access.
JDBC Drivers
Type I: JDBC-ODBC bridge driver Type II: Native-API partly Java driver Type III: JDBC-Net pure Java driver Type IV: Native protocol pure Java driver
JDBC Architectures
Java Application
JDBC/ODBC bridge
JDBC/native bridge
ODBC Driver
DBMS
1) Importing Packages import java.sql.*; 2) Registering the driver Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); OR Driver d=new sun.jdbc.odbc.JdbcOdbcDriver(); DriverManager.registerDriver(d);
3) Connecting to DataBase Connection con = DriverManager.getConnection (jdbc:odbc:datasourcename, username, password); 4) Create a statement object Statement stmt=con.createStatement();
5) Executing a Query and returning a ResultSet object ResultSet rs= stmt.executeQuery ( SELECT * from authors); 6) Close the statement and the connection stmt.close(); con.close();
Statement Methods
ResultSet executeQuery(String) Execute a SQL statement that returns a single ResultSet. int executeUpdate(String) Execute a SQL INSERT, UPDATE or DELETE statement. Returns the number of rows changed. boolean execute(String) Execute a SQL statement and returns a boolean value.
ResultSet
A ResultSet provides access to a table of data generated by executing a Statement. Only one ResultSet per Statement can be open at once. The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The 'next' method moves the cursor to the next row. you cant rewind
while(rs.next()) { System.out.println(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3)); } First column has index 1, not 0 The ResultSet provides getXxx methods that take a column index or column name and returns the data Can also access result meta data (column names, etc.)
ResultSet Methods
Type getType(int columnIndex) returns the given field as the given type Type getType(String columnName) same, but uses name of field less efficient
yes
More results no closeStatment closeConnection
Scrollable ResultSet
Statement createStatement( resultSetType, resultSetConcurrency)
resultSetType:
ResultSet.TYPE_FORWARD_ONLY -allows only forward movement of the cursor
ResultSet.TYPE_SCROLL_INSENSITIVE
-backwards, forwards, random cursor movement. -does not reflect the changes in the data. ResultSetTYPE_SCROLL_SENSITIVE -backwards, forwards, random cursor movement. - reflect the changes in the data.
This is the default and allows only data to be read from the database.
ResultSet.CONCUR_UPDATABLE This option allows to make changes to the database based on new methods and positioning ability of the cursor. Example: Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs= stmt.executeQuery(str);
public boolean absolute(int row) throws SQLException -If the given row number is positive, this method moves the cursor to the given row number (with the first row numbered 1).
-If the row number is negative, the cursor moves to a relative position from the last row.
-If the row number is 0, an SQLException will be raised. public boolean relative(int row) throws SQLException Shifts the control of a result set cursor, forward or backward, relative to the row number that you specify as a parameter. This method accepts either a positive or negative value as a parameter.
Updatable ResultSet
void updateRow() void insertRow() void deleteRow() void updateString() void updateInt()
Querying with
PreparedStatement
String str = "SELECT * FROM employee " + "WHERE emp_id= ? and salary > ?";
PreparedStatement ps = con.prepareStatement(str);
Updating with
PreparedStatement
String str = DELETE FROM employee " + "WHERE emp_id = ? and salary > ?";
PreparedStatement ps = con.prepareStatement(str);
If one fails, the system must reverse all previous actions Also cant leave DB in inconsistent state halfway through a transaction COMMIT = complete transaction ROLLBACK = cancel all actions
Example
Suppose we want to transfer money from bank account 13 to account 72:
PreparedStatement ps = con.prepareStatement("update BankAccount set amount = amount + ? where accountId = ?"); ps.setInt(1,-100); ps.setInt(2, 13); ps.executeUpdate(); What happens if this ps.setInt(1, 100); update fails? ps.setInt(2, 72); ps.executeUpdate();
Transaction Management
Transactions are not explicitly opened and closed The connection has a state called AutoCommit mode if AutoCommit is true, then every statement is automatically committed if AutoCommit is false, then every statement is added to an ongoing transaction Default: true
AutoCommit
setAutoCommit(boolean val) If you set AutoCommit to false, you must explicitly commit or rollback the transaction using con.commit() and con.rollback() Note: DDL statements (e.g., creating/deleting tables) in a transaction may be ignored or may cause a commit to occur
Save Points
Statement st=con.createStatement( ); st.executeUpdate(str1); Savepoint svpt=con.setSavepoint( ); st.executeUpdate(str2); if() conn.rollback(svpt); . con.commit( );
Batch Updates
A batch is a group of update statements that are sent to a database to be executed as a single unit. You can send the batch to a database in a single request using the same Connection object. Reduces network calls between the application and the database. Disable the auto-commit mode so that you can rollback the transaction.
Batch Updates
con.setAutoCommit(false); Statement stmt=con.createStatement( ); stmt.addBatch(INSERT INTO product (p_id, p_desc) VALUES (1001,Printer ) ); stmt.addBatch(INSERT INTO product (p_id, p_desc) VALUES (1002,Scanner ) ); int[ ] count=stmt.executeBatch( ) ;
Metadata
It gives the information about the data such as structure and properties of the table. JDBC API provides the following two metadata interfaces to retrieve the information about the data base and result set DatabaseMetaData interface ResultSetMetaData interface
DatabaseMetaData
Provides the methods that enable you to determine the properties of a database. Provides information such as: Names of database tables Database version Use the following method call to create an object of the DatabaseMetaData interface: DatabaseMetaData dbmd=con.getMetaData( );
Methods of DatabaseMetaData
String getDriverName( ) Retrieves the name of the JDBC driver String getDriverVersion( ) Retrieves the version of the JDBC driver String getURL( ) Retrieves the URL of the database. boolean isReadOnly( ) Indicates whether the database is read only database
ResultSet MetaData
A ResultSetMetaData is an object that can be used to get information about the properties of the columns in a ResultSet object. Provides information such as:
Number of columns Names of columns Data types of the columns ResultSetMetaData rsmd=rs.getMetaData( );
Methods of ResultSetMetaData
int getColumnCount( ) String getColumnName(int column_index) String getTableName(int column_index) int getColumnType(int column_index) boolean isCaseSensitive(int column_index) boolean isReadOnly(int column_index)
Row Sets
RowSet interface extends the ResultSet interface. Row sets dont have to be tied to a database connection. Some of the interfaces that extend the RowSet interface: CachedRowSet WebRowSet FilteredRowSet and JoinRowSet JdbcRowSet
ResultSet rs=stmt.executeQuery(str); CachedRowSet rowset=new com.sun.rowset.CachedRowSetImpl( ); rowset.populate(rs); con.close( ); rowset.acceptChanges(con); OR rowset.setURL(.); rowset.setUsername(); rowset.setPassword(); rowset.setcommand(SELECT * FROM Books); rowset.execute( ); rowset.acceptChanges( );