Вы находитесь на странице: 1из 44

UNIT-3

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

JDBC/ODBC bridge

JDBC/native bridge

JDBC middleware JDBC Driver (various DBMS) (DBMS Specific)

ODBC Driver

Native driver (DBMS specific)

DBMS

JDBC Class Usage


DriverManager Driver Connection Statement ResultSet

The JDBC Steps


1. Importing Packages 2. Registering the JDBC Drivers 3. Opening a Connection to a Database 4. Creating a Statement Object 5. Executing a Query and Returning a Result Set Object 6. Processing the Result Set 7. Closing the Statement Object 8. Closing the Connection

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

A Simple JDBC application


import java.sql.*; public class jdbctest { public static void main(String args[]){ try{ Class.forName(sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection (jdbc:odbc:mydatasource", "user", "passwd"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery ("select name, number from pcmtable where number < 2"); while(rs.next()) System.out.println(rs.getString(1) + " (" + rs.getInt(2) + ")"); stmt.close() con.close(); } catch(Exception e){ }}}

loadDriver getConnection createStatement execute(SQL) Result handling

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.

Scrollable ResultSet (contd)


resultSetConcurrency: ResultSet.CONCUR_READ_ONLY

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.

Scrollable ResultSet (contd)


public boolean first() public boolean last()

public boolean previous()


public boolean next() public void beforeFirst()

public void afterLast()


public boolean isFirst() public boolean isLast()

public boolean isAfterLast()


public boolean isBeforeFirst() public int getRow()

Updatable ResultSet
void updateRow() void insertRow() void deleteRow() void updateString() void updateInt()

About Prepared Statements


Allows you to pass runtime parameters to the SQL statements to query and modify the data in a table. Also used for queries that are executed many times.

Complied and prepared only once by JDBC.

About Prepared Statements(cnt..)


Helps in reducing the load on the database server and thus improving the performance of the application. Instead of values, use ?. Hence, Prepared Statements can be thought of as statements that contain placeholders to be substituted later with actual values.

Querying with
PreparedStatement
String str = "SELECT * FROM employee " + "WHERE emp_id= ? and salary > ?";
PreparedStatement ps = con.prepareStatement(str);

ps.setString(1, "34562"); ps.setInt(2, 26000); ResultSet rs = ps.executeQuery();

Updating with
PreparedStatement
String str = DELETE FROM employee " + "WHERE emp_id = ? and salary > ?";
PreparedStatement ps = con.prepareStatement(str);

ps.setString(1, "34562"); ps.setDouble(2, 26000);


int count = ps.executeUpdate();

Statements vs. PreparedStatements


Are these the same? What do they do?
String val = "abc"; PreparedStatement ps = con.prepareStatement("select * from R where A=?"); ps.setString(1, val); ResultSet rs = pstmt.executeQuery(); String val = "abc"; Statement stmt = con.createStatement( ); ResultSet rs = stmt.executeQuery("select * from R where A=" + val);

Statements vs. PreparedStatements


Will this work?
PreparedStatement ps = con.prepareStatement("select * from ?"); ps.setString(1, myFavoriteTableString);

No!!! A ? can only be used to represent a column value

Transactions and JDBC


Transaction: more than one statement that must all succeed (or all fail) together
e.g., updating several tables due to customer purchase

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

Cached Row Sets


Contains all data from a result 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. You can also modify the data in a cached row set. You need to make an explicit request to accept the accumulated changes. Not appropriate for large query results.

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

JDBC Class Diagram

Вам также может понравиться