oracle+applications+using+java+&+jdbc

82
ORACLE APPLICATIONS USING JAVA & JDBC CIS 612 – Topics on Advanced Database Systems Victor Matos

Upload: venkat

Post on 29-Sep-2015

2 views

Category:

Documents


0 download

DESCRIPTION

jdbc database programming

TRANSCRIPT

  • ORACLE APPLICATIONS USING JAVA & JDBCCIS 612 Topics on Advanced Database SystemsVictor Matos

  • What is JDBC ?JDBC (Java database connectivity) is an API for the Java programming language that defines how a client may access a database.

    It provides methods for querying and updating data in a database.

    JDBC is oriented towards relational databases.

    It was originally included in the Java 2 Platform, Standard Edition, version 1.4 (J2SE) (1997).*

  • JDBC Architecture Components*JDBC 4.0 Specification. JSR 221Lance Andersen, Specification LeadNovember 7, 2006

  • What is JDBC ? - ComponentsJDBC connections support creating and executing statements.

    Statements may be action commands such as: SQL CREATE, INSERT, UPDATE and DELETE or they may be query statements using the SELECT statement. Stored procedures may also be invoked through a statement.

    Statements are one of the following types:Statement the statement is sent to the database server each and every time. PreparedStatement the statement is cached and then the execution path is pre determined on the database server allowing it to be executed multiple times in an efficient manner. CallableStatement used for executing stored procedures on the database.

    *

  • What is JDBC ? - ComponentsUpdate statements such as INSERT, UPDATE and DELETE return an update count that indicates how many rows were affected in the database. These statements do not return any other information. Query statements return a JDBC row ResultSet. The row result set is used to traverse the result set. Individual columns in a row are retrieved either by name or by column number. There may be any number of rows in the result set. The row result set has metadata that describes the names of the columns and their types.

    *

  • What is JDBC ? - Components*A ResultSet is a Java object that contains the rows resulting from executing a SQL query. The data stored in a ResultSet object is retrieved with various getXXX methods that allows access to the columns of the current row. The .next method is used to move to the next row of the ResultSet. The Statement methods executeQuery and getResultSet both return a ResultSet object.

    ExampleStatement stmt = conn.createStatement();ResultSet rs = stmt.executeQuery (select * from employee);

  • A Brief Example How do JDBC apps look like?*A JDBC based application makes possible to do three things: Establish a connection with a data source Send queries and update statements to the data source Process the results

  • A Brief Example How JDBC apps look like*Typical Code Fragment

    Class.forName("oracle.jdbc.OracleDriver");String URL = "jdbc:oracle:thin:@localhost:1521:XE";Connection con = DriverManager.getConnection( URL, "myUserName", "myPassword");

    Statement stmt = con.createStatement(); String mySQL = "select fName, salary from employee"; ResultSet rs = stmt.executeQuery(mySQL);

    while (rs.next()) { String fName = rs.getString("fName"); float salary = rs.getFloat("salary"); //... Do some work with the data} 123

  • Download JDBC Driver*(Oracle) http://java.sun.com/products/jdbc/overview.html(MS SQL Server) http://msdn2.microsoft.com/en-us/data/aa937724.aspx(MySQL) http://www.mysql.com/products/connector/j/

  • Setting Up The SQL2005 JDBC Drivers*Setting the ClasspathThe JDBC driver is not part of the Java SDK. Therefore, you must set the classpath to include the sqljdbc.jar file if you want to use it. If the classpath is missing an entry for sqljdbc.jar, your application will throw the common "Class not found" exception. The sqljdbc.jar file is installed in the following location:\sqljdbc_\\sqljdbc.jar

    The following is an example of the CLASSPATH statement that is used for a Windows application:CLASSPATH =.;C:\Program Files\Microsoft SQL Server 2005 JDBC Driver\sqljdbc_1.2\enu\sqljdbc.jar

  • Setting Up The SQL2005 JDBC Drivers*Making a Simple Connection to a Microsoft SQL-Server-2005 DatabaseTo connect to a MSSQL2005 database by using the DriverManager class, you must first register the driver as follows:Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); When the driver is loaded, you can establish a connection by using a connection URL:

    String connectionUrl = "jdbc:sqlserver://localhost:1433;" + "databaseName=Northwind; + "user=MyUserName;password=*****;" ; Connection con = DriverManager.getConnection(connectionUrl);

  • JDBC Drivers *There are four types of JDBC drivers. Each type provides an increasingly higher levels of platform independence, performance, and deployment administration.

    Type 1: JDBC-ODBC Bridge Type 2: Native-API/partly Java driver Type 3: Net-protocol/all-Java driver Type 4: Native-protocol/all-Java driver

  • JDBC Drivers. Type1: JDBC-ODBC Bridge *The JDBC-ODBC Bridge, translates all JDBC calls into ODBC calls and sends them to the local ODBC driver. The ODBC driver must be present on the client machine.

    AdvantagesThe JDBC-ODBC Bridge allows access to almost any database. Type 1 drivers may be useful for those companies that have an ODBC driver already installed on client machines. DisadvantagesPerformance is compromised since JDBC calls go through the bridge to the local ODBC driver, then to the native database connectivity interface. Type 1 drivers may not be suitable for large-scale applications. Have the same deployment problems of traditional applications.

  • JDBC Drivers - JDBC-ODBC Bridge *JDBC-ODBC BridgeODBC DriveVendor DB LibraryApplicationDatabaseServerClient MachineServer Machine

  • JDBC Drivers - Type 4: Native-protocol/all-Java driver*JDBC driver type 4 converts JDBC calls into vendor-specific DBMS protocol behavior so that client applications can communicate directly with the database server.

    AdvantagesType 4 JDBC drivers dont have to translate database requests to ODBC or a native connectivity interface therefore performance is typically good. Theres no need to install special software on the client or server. Drivers can be downloaded dynamically.

    DisadvantagesWith type 4 drivers, the user needs a different driver for each database.

  • *JDBC Drivers Type 4: Native Protocol Pure Java Driver*JDBC Native Protocol Pure Java DriverApplicationDatabaseServerClient MachineServer Machine

  • *JDBC DriverManager Object*The DriverManager typically registers a particular Driver class by means of the following statement

    Class.forName("oracle.jdbc.OracleDriver")This method explicitly loads the driver class. It does not depend on any external setup.

  • JDBC Connection Object*Connection OverviewA Connection object represents a link/pipe leading to/from a database. A connection session includes the SQL statements that are executed and the results that are returned over that connection. A single application can have one or more connections with a single database, or it can have connections with many different databases.

    Opening a Connection The typical way to establish a connection with a database is to call the method DriverManager.getConnection (URL,). The DriverManager class attempts to locate a driver that can connect to the database represented by that URL. The DriverManager class maintains a list of registered Driver classes, and when the method getConnection is called, it checks with each driver in the list until it finds one that can connect to the database specified in the URL.

  • JDBC Connection Object*Example: This fragment illustrates the loading of the Oracle JDBC driver and the setting of a connection using the jdbc.thin driver to the local database instance identified as XE for user= csuperson using password= Euclid.

    //register the Oracle JDBC driverClass.forName("oracle.jdbc.OracleDriver");

    //you may replace "localhost" by "127.0.0.1" //or real TCPConnection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","csuperson", "euclid");

  • JDBC Statement Object*The JDBC API provides three interfaces for sending SQL statements to the database.A Statement object is used for sending SQL statements with no parameters. PreparedStatement object is used for precompiled SQL statements. These can take one or more parameters as input arguments. A PreparedStatement object has the potential to be more efficient than a Statement object because it has been precompiled and stored for future use. CallableStatement objects are used to execute SQL stored procedures. A CallableStatement object has mechanisms for dealing with IN, OUT and INOUT parameters.

  • JDBC Statement Object*Methods supporting Statement objects

    createStatement methods-for a simple SQL statement (no parameters) prepareStatement methods-for an SQL statement that is executed frequently prepareCall methods-for a call to a stored procedure

  • JDBC Statement Object*Creating Statement ObjectsOnce a connection to a particular database is established, that connection can be used to send SQL statements. A Statement object is created with the method createStatement, as in the following code fragment:

    conn = DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:XE", "csuperson", "euclid" );Statement stmt = conn.createStatement();ResultSet rset = stmt.executeQuery ("select Salary, Fname from employee");

    The variable rset references a forward-only, read-only result set.

  • JDBC Statement Object*Executing StatementsThe Statement interface provides three different methods for executing SQL statements: executeQuery, executeUpdate, and execute.

    executeQuery is designed for statements that produce a single result set, such as SELECT statements.

    executeUpdate is used to execute INSERT, UPDATE, or DELETE statements and also SQL DDL (Data Definition Language) statements like CREATE TABLE, DROP TABLE, and ALTER TABLE. The return value of executeUpdate is an integer (referred to as the update count) that indicates the number of rows that were affected. For statements such as CREATE TABLE or DROP TABLE, which do not operate on rows, the return value of executeUpdate is always zero.

    execute is used to execute statements that return more than one result set, more than one update count, or a combination of the two.

  • JDBC Statement Object*Statement CompletionWhen a connection is in auto-commit mode, the statements being executed within it are committed or rolled back when they are completed.

    A statement is considered complete when it has been executed and all its results have been returned. For the method executeQuery, which returns one result set, the statement is completed when all the rows of the ResultSet object have been retrieved. For the method executeUpdate, a statement is completed when it is executed.

  • JDBC Statement Object*Closing StatementsStatement objects will be closed automatically by the Java garbage collector.

    However it is recommended as good programming practice that they be closed explicitly when they are no longer needed.

  • JDBC Statement Object* Returning an Update Count Statements invoking an action SQL query return the number of rows affected by the maintenance operation. Some DML operations that do not produce rows return the value zero.

    Statement stmt = conn.createStatement(); String mySQL = "Update Employee set dno=1 where ssn=123456789"; int myRows = stmt.executeUpdate(mySQL); if (myRows > 0) {//record found update applied!... }

    The method executeUpdate throws an SQLException if the SQL string beingexecuted returns a ResultSet.

  • JDBC Statement Object* Using UpdateXXX StatementsAssume the DEPARTMENT table schema is as follows< DNAME, DNUMBER, MGRSSN, MGRSTARTDATE >The following statements locally update the rs result set that is produced after evaluating a SQL query. The .updateRow (or .cancelRowUpdates) method is used to commit (or roll-back) the changes.

    rs.absolute(4);rs.updateString (1, "International Sales");rs.updateLong (3, 123456789);rs.updateRow();The 4th row of the result set is fetched. The 1st column (DNAME) is changed to International Sales, its 3rd column (MGRSSN) is changed to 123456789. All the changes to the row are committed with the .updateRow() method.

  • JDBC Statement Object* Using UpdateXXX Statements (cont.)Assume the DEPARTMENT table schema is as follows< DNAME, DNUMBER, MGRSSN, MGRSTARTDATE >The following statements locally update the rs result set that is produced after evaluating a SQL query. The .updateRow (or .cancelRowUpdates) method is used to commit (or roll-back) the changes.

    rs.absolute(4);rs.updateString ("DNAME", "International Sales");rs.updateLong ("MGRSSN", 123456789);rs.updateRow();The 4th row of the result set is fetched. The 1st column (DNAME) is changed to International Sales, its 3rd column (MGRSSN) is changed to 123456789. All the changes to the row are committed with the .updateRow() method.

  • JDBC ResultSet Object*Deleting a RowThe deleteRow method deletes the current row. Before calling deleteRow, an application must position the cursor on the row it wants to delete. This method affects both the current row in the result set and the underlying row in the database.

    Example. The following two lines of code remove the first row of the ResultSet object rs and also delete the underlying row from the database (which may or may not be the first row of the database table). rs.first(); rs.deleteRow();

  • JDBC ResultSet Object*Inserting RowsNew rows may be inserted into an updatble result set and into the underlying database table using the insertRow method.The moveToInsertRow call positions the cursor on the insert row. updateXXX methods add column values to the insert row. When all of the columns of the row to be inserted have been set, the application calls the method insertRow. This method adds the insert row to both the result set and the underlying database simultaneously. Finally, the application needs to position the cursor on a row back in the result set.

    Example. The following code fragment demonstrates these steps for inserting a row from an application written in the Java programming language.

    rs.moveToInsertRow();rs.updateObject (1, myListPeople);rs.updateInt (2, 101);rs.updateString (3, "Automation Project");rs.insertRow();rs.first();

  • JDBC Statement Object*Batch UpdatesExample. An application uses a try/catch block, and if a BatchUpdateException is thrown, it retrieves the exception's array of update counts to discover which commands in a batch update executed successfully before the BatchUpdateException object was thrown.

    Statement stmt = conn.createStatement(); conn.setAutoCommit(false); try { stmt.addBatch ("INSERT INTO works_on VALUES (777888999, 10, 35)" );stmt.addBatch ("INSERT INTO works_on VALUES (777888999, 20, 2)" );stmt.addBatch ("INSERT INTO works_on VALUES (777888999, 30, 3)" ); int [] updateCounts = stmt.executeBatch(); } catch(BatchUpdateException b) { System.err.println("Update counts of successful commands: "); int [] updateCounts = b.getUpdateCounts(); for (int i = 0; i < updateCounts.length; i ++) { System.err.print(updateCounts[i] + " "); } System.err.println(""); }

  • JDBC PreparedStatement Object*Using a Prepared Statement to Create Result SetsThe following code fragment creates a result set using a PreparedStatement object.

    Class.forName("oracle.jdbc.OracleDriver");Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","csuperson", "euclid");

    String mySQL = "select hours from works_on where sex= ? And pno= ? ";PreparedStatement pstmt = conn.prepareStatement( mySQL, ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); pstmt.setFetchSize(25); pstmt.setString(1, "F"); pstmt.setInt(2, 10); ResultSet rset = pstmt.executeQuery();

    The variable rset contains the HOURS value for the row where the SSN value is 123456789 and PNO is 10. The ResultSet object is scrollable, updatable, sensitive to changes in its data, and fetches 25 rows at a time from the database.

  • JDBC PreparedStatement Object*Using a Prepared Statement to Create Result Sets

    select hours from works_on where sex= ? And pno= ?

    pstmt.setInt(1, F);

    pstmt.setInt(2, 10); 12

  • JDBC CallableStatements*CallableStatement Overview

    A CallableStatement object provides a way to call stored procedures in a standard way for all RDBMSs.

    A stored procedure is stored in a database

    CallableStatements accept IN, OUT and INOUT parameters.

    { ? = call FunctionProcName ( ? ) }OUTIN

  • JDBC CallableStatements*Stored Procedures and FunctionsIf a database supports stored procedures, they can be invoked using JDBC escape syntax as follows:

    { call [ ( ) ] }or, where a procedure returns a result parameter:{ ? = call [ ( ) ] }

    The square brackets indicate that the (argument-list) portion is optional. Input arguments may be either literals or parameter markers.

  • JDBC CallableStatements*Assume the following Stored PL/SQL function is available in our Oracle server

    FUNCTION getName ( theSSN IN NUMBER ) RETURN VARCHAR2IS theTotal NUMBER; theName VARCHAR2(40);BEGIN --Accept SSN and return full name of requested employee select count(*) into theTotal from employee where SSN = theSSN; if (theTotal = 0) then RETURN(''); else select (FName || ' ' || Lname) into theName from employee where SSN = theSSN; RETURN (theName); end if;EXCEPTION when others thenreturn ('***ERROR***');END;DBMS

    Data+Stored ProceduresMmmmMmmmmmmMmmmMmmmmmmMmmmMmmmMm m

  • JDBC CallableStatements*Invoking stored procedureCallableStatement cstmt = conn.prepareCall( " { ? = call getName ( ? ) } " ); //register parameter TYPEscstmt.registerOutParameter (1, Types.VARCHAR);cstmt.registerInParameter (2, java.sql.Types.INTEGER);//set SSN value to identify employeecstmt.setLong (2, 123456789);cstmt.execute ();// Retrieve OUT parametersString fullName = cstmt.getString (1);

    System.out.println("result is ==> " + fullName);O U T

    1IN

    2

  • ResultSet Object*Processing a Data Row from a ResultSetIn the example below expression: rs.getInt(0) is equivalent to rs.getInt(SSN)

    Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT ssn, fName, salary FROM employee"); while (rs.next()) { // retrieve and print the values for the current row int mySSN = rs.getInt(SSN"); String myFName = rs.getString(fName"); float mySalary = rs.getFloat(salary"); System.out.println("ROW => " + mySSN + " " + myFName + " " + mySalary); }

  • ResultSet Object*

  • ResultSet Object*Determining the Number of Rows in a Result Set

    String mySQL = "SELECT * FROM employee";ResultSet rs = stmt.executeQuery(mySQL); rs.last(); int numberOfRows = rs.getRow(); System.out.println(" Employee table size: " + numberOfRows );rs.beforeFirst(); while (next()) { // do some work here with the EMPLOYEE records. . . }

  • ResultSet Objects*Example: ResultSet Concurrency

    Connection conn = ds.getConnection(user, passwd);Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY,ResultSet.CLOSE_CURSORS_AT_COMMIT);

    This example creates a Statement object that will return scrollable, read-only ResultSet objects that are insensitive to updates made to the data source and that will be closed when the transaction in which they were created is committed.

  • ResultSet Objects*Types of ResultSets

    TYPE_FORWARD_ONLY The result set is non-scrollable; its cursor moves forward only, from top to bottom.

    TYPE_SCROLL_INSENSITIVE The result set is scrollable: Its cursor can move forward or backward and can be moved to a particular row or to a row whose position is relative to its current position. Changes made to the underlying database are not reflected in the ResulSet while it is open.

    TYPE_SCROLL_SENSITIVE The result set is scrollable; its cursor can move forward or backward and can be moved to a particular row or to a row whose position is relative to its current position. The result set is sensitive to changes made to the underlying database while it is open.

  • ResultSet Objects*Concurrency TypesA result set is by default READ_ONLY may however this could be changed.

    CONCUR_READ_ONLY This allow users to read (unlocked) data but not to change it.

    CONCUR_UPDATABLE Indicates a result set that can be updated programmatically. Updatable results sets may use write-only locks so that only one user at a time has access to a data item.

  • JDBC ResultSet Class*

    Cursor Movement next() moves the cursor forward one row. Returns true if the cursor is now positioned on a row and false if the cursor is positioned after the last row. previous() moves the cursor backwards one row. Returns true if the cursor is now positioned on a row and false if the cursor is positioned before the first row. first() moves the cursor to the first row in the ResultSet object. Returns true if the cursor is now positioned on the first row and false if the ResultSet object does not contain any rows. last() moves the cursor to the last row in the ResultSet object. Returns true if the cursor is now positioned on the last row and false if the ResultSet object does not contain any rows. beforeFirst() positions the cursor at the start of the ResultSet object, before the first row. If the ResultSet object does not contain any rows, this method has no effect. afterLast() positions the cursor at the end of the ResultSet object, afterthe last row. If the ResultSet object does not contain any rows, this method has no effect. relative(int rows) moves the cursor relative to its current position. absolute(int row) positions the cursor on the row-th row of the ResultSet object.

  • *ResultSet Objects*Positioned Updates and DeletesJDBC drivers or DBMSs that do not support performing updates via the ResultSet interface may support positioned updates and deletes via SQL commands.EXAMPLEStatement stmt1 = conn.createStatement();stmt1.setCursorName(CURSOR1);ResultSet rs = stmt1.executeQuery(select * from employee for update of salary);// move to the row we want to updatewhile ( ... ) {rs.next()}String cursorName = rs.getCursorName();Statement stmt2 = conn.createStatement();// now update the rowString mySQL = "update employee set salary = salary + 0.10 where current of + cursorName;int updateCount = stmt2.executeUpdate(mySQL);

  • ResultSet: Updating a Row*Updating a row in a ResultSet object is a two-phase process. The new value for each column being updated is set, and The change is applied to the row.

    The row in the underlying data source is not updated until the second phase is completed.

    ExampleStatement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);ResultSet rs = stmt.executeQuery(select * from employee where ssn = 123456789) ;rs.next();//replace (old) Last name with new value: Macarenars.updateString(Lname, Macarena);rs.updateRow();

  • ResultSet: Deleting a Row*A row in a ResultSet object can be deleted using the method deleteRow.

    EXAMPLE //remove the fourth row of the ResultSet rs rs.absolute(4);rs.deleteRow();

  • ResultSet: Inserting a Row*The steps to insert a new row are:Move the cursor to the insert rowSet the values for the columns of the row using the ResultSet interface update methodsInsert the new row into the ResultSet object

    EXAMPLE // assign employee 123456789 to project No. 10 a total of 2.5 hours/week// select all the columns from the WORKS_ON(ESSN, PNO, HOURS) table ResultSet rs = stmt.executeQuery(select * from Works_On );rs.moveToInsertRow();// set values for each columnrs.updateString(1, 123456789);rs.updateInt(2, 10);rs.updateFloat(3, 2.5);// insert the rowrs.insertRow();// move the cursor back to its position in the result set all done!rs.moveToCurrentRow();

  • NULL values*NULL Result ValuesA JDBC NULL retrieved by one of the ResultSet.getXXX methods is converted to either null, 0, or false, depending on the type of the value. Returned Valuesnull-for those getXXX methods that return objects in the Java programming language (getString, getBigDecimal, getBytes, getDate, getTime, getTime-stamp, getAsciiStream, getCharacterStream, getUnicodeStream, getBinary-Stream, getObject, getArray, getBlob, getClob, and getRef) 0 (zero)-for getByte, getShort, getInt, getLong, getFloat, and getDouble false-for getBoolean

    Example. If the method getDouble returns 0 from a column that allows null values an application could call the method wasNull to determine if the original value was NULL.

    double c = rs.getDouble("Commission");boolean b = rs.wasNull();

    The method wasNull checks only the last value retrieved. If b is true, the value stored in the third column of the current row of rs is JDBC NULL.

  • Transaction Processing*Committing ChangesBy default, data manipulation language (DML) operations are committedautomatically as soon as they are run. This is known as the (Oracle) auto-commit mode. However, you can disable auto-commit mode with the following method call on the Connection object:conn.setAutoCommit(false);If you disable the auto-commit mode, then you must manually commit or roll back changes with the appropriate method call on the Connection object:conn.commit();or:conn.rollback();Note: A COMMIT or ROLLBACK operation affects all DML statements run since the last COMMIT or ROLLBACK.

  • JDBC - Support Classes*If you are using Jdeveloper 11g make sure you include the Oracle JDBC Library to your application.

    If you are using Eclipse (or other Java IDE) the following JAR files must be needed to the app.C:\JDeveloper11G\jlib\dms.jarC:\JDeveloper11G\jlib\ojdl.jarC:\JDeveloper11G\jlib\orai18n.jarC:\JDeveloper11G\jdbc\lib\ojdbc5dms.jar

  • JDBC - Support Classes*JDeveloper11g from Oraclehttp://www.oracle.com

    SUN - JDBC and Database Pagehttp://java.sun.com/javase/technologies/database/index.jsp

  • Eclipse IDE JDBC Support Classes*

  • Jdeveloper 11g JDBC Support Classes*

  • Example1. Using a Local ODBC DataSource*package JavaJDBCDemo1;import java.sql.*;public class JavaJDBCDemo1 { public static void main(String[] args) { try { //create a jdbc to odbc bridge Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //there is a local ODBC data source already defined under the name: myOracleODBC to access //the Oracle instance using credentials: user=csuperson, password=euclid String database = "jdbc:odbc:myOracleODBC"; Connection con = DriverManager.getConnection( database ,"csuPerson","euclid"); Statement s = con.createStatement(); //Using the Statement class: create a table, populate, query and drop it s.execute("create table myTable ( myCol1 integer, myCol2 varchar2(20) )"); s.execute("insert into myTable values(11, 'AAA')"); // insert data into the table s.execute("insert into myTable values(22, 'BBB')"); // insert data into the table s.execute("select * from myTable"); // select data from the table ResultSet rs = s.getResultSet(); // get ResultSet from query Exampe1. Use an ODBC-JDBC Bridge to reach Oracle and create, populate, query, and drop a table.Assuming ODBC data source already set.

  • Example1. Using a Local ODBC DataSource cont.* //if rs == null, then there is no ResultSet to view if (rs != null) while ( rs.next() ) // this loop will step through our data row-by-row { //alternatively use: rs.getInt(1) or rs.getString(2) System.out.println(" myCol1: " + rs.getInt("myCol1") + " myCol2: " + rs.getString("myCol2")); }//end while s.execute("drop table myTable"); s.close(); con.close(); } //end if

    catch (Exception e) { System.out.println("Error: " + e); } }//end main}//end class

    Exampe1. Use an ODBC-JDBC Bridge to reach Oracle and create, populate, query, and drop a table

  • Example1. Using a Local ODBC DataSource cont.*Exampe1. Use an ODBC-JDBC Bridge to reach Oracle and create, populate, query, and drop a table

  • Example1B. Using Thin JDBC Layer*Exampe1. Use an ODBC-JDBC Bridge to reach Oracle and create, populate, query, and drop a tableWe will modify the previous Example1 to by-pass the local ODBC data source and directly go to the database server using the Thin JDBC driver. This approach should be more efficient. You need to make the following code changes:

    Class.forName ("oracle.jdbc.OracleDriver"); String database = "jdbc:oracle:thin:@localhost:1521:XE"; Connection con = DriverManager.getConnection( database ,"csuPerson","euclid");

    You must add the Oracle JDBC driver to the applications path. For example, in this case we added all the .jar files from the folderc:\Jdeveloper\jdbc\lib

  • Example2. Using JDBC Thin Driver (1/3)*package JavaAccessDB2Thin;

    import java.sql.*;

    // Example shows how to list the names from the EMPLOYEE table. It uses the JDBC THIN driver // you must add the Oracle.jdbc library to the applications path.

    class JavaAccessDB2ThinDriver{ public static void main (String args []) throws SQLException, ClassNotFoundException { Connection conn = null; System.out.println("Loading Oracle thin driver"); // Load the Oracle JDBC driver Class.forName ("oracle.jdbc.OracleDriver"); System.out.println("Driver manager created");

    //------------------------------------------------------------------------ // Connect to the database. // You must put a database name after the @ sign in the connection URL. // You can use either the fully specified SQL*net syntax or a short cut // syntax as ::. The example uses the short cut syntax. //------------------------------------------------------------------------

    Example2. Use the JDBC Thin Driver to create a ResultSet holding the SSN and name of each employee in the COMPANY database.

  • Example2. Using JDBC Thin Driver (2/3)*

    try {conn = DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:XE", "csuperson", "euclid"); if (conn != null) { System.out.println("Connection created for CSUPERSON/EUCLID"); } else { System.out.println("***No connection was created"); } // Create a Statement Statement stmt = conn.createStatement (); System.out.println("***Statement created");

    // Select the FNAME column from the EMPLOYEE table ResultSet rset = stmt.executeQuery ( " select (FNAME || ' ' || LNAME) as FullName " + " from EMPLOYEE " + " where SEX in ('F', 'M') "); System.out.println("***OK. Query executed");

    // Iterate through the result and print the employee names while (rset.next ()) { System.out.println (Full name: " + rset.getString (1)); } }Example2. Use the JDBC Thin Driver to create a ResultSet holding the SSN and name of each employee in the COMPANY database.

  • Example2. Using JDBC Thin Driver (3/3)*

    catch (SQLException e) {System.out.println("Test threw a " + e.getClass() + "\n with message: " + e.getMessage() + " : Error code (" + e.getErrorCode() + ")" ); }

    // Clean up connection is there was one finally { if(conn != null) { conn.close(); System.out.println("***Connection closed"); } else { System.out.println("***There was no connection"); }

    } }}

    Example2. Use the JDBC Thin Driver to create a ResultSet holding the SSN and name of each employee in the COMPANY database.//TRY THIS://connecting to a remote Oracle11g (ORCL) server located in SANCHO.CSUOHIO.EDUconn = DriverManager.getConnection( "jdbc:oracle:thin:@sancho.csuohio.edu:1521:ORCL", "csuperson", "euclid");

  • Connection Strings*Connecting to a Remote ORACLE Server

    // Load the Oracle JDBC driverClass.forName("oracle.jdbc.OracleDriver");//connecting to a remote Oracle11g (ORCL) server located in SANCHO.CSUOHIO.EDUconn = DriverManager.getConnection( "jdbc:oracle:thin:@sancho.csuohio.edu:1521:ORCL", "csuperson", "euclid");

  • Connection Strings*Connecting to a Remote MS-SQL2005 Server accepting Windows Authentication and Trusted SQL connections

    // Load the Microsoft JDBC driver for SQL2005 ServerClass.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");//Connecting to local version of SQL2005 running in local computer// String connectionUrl = "jdbc:sqlserver://localhost:1433; "user=csuperson2;" "password=euclid2; + // "trusted connection=false;" + "databaseName=Company;";

    // connecting to remote SQL2005 Server called SANCHO.CSUOHIO.EDUString connectionUrl = "jdbc:sqlserver://sancho.csuohio.edu:1433;"+ "user=csuperson2;" + "password=euclid2;"+ "trusted connection=false;" + "databaseName=Company;";Connection con = DriverManager.getConnection(connectionUrl);

  • Example3. Calling a PL/SQLFunction 1/5*The following PL/SQL function accepts a Social Sec. Number, if a match is found it returns the employees full name.

    FUNCTION getName ( theSSN IN NUMBER ) RETURN VARCHAR2IS theTotal NUMBER; theName VARCHAR2(40);

    BEGIN select count(*) into theTotal from employee where SSN = theSSN;

    if (theTotal = 0) then RETURN(''); else select (FName || ' ' || Lname) into theName from employee where SSN = theSSN; RETURN (theName); end if;

    EXCEPTION when others thenreturn ('***ERROR***');END;Example3. Use the JDBC Thin Driver to invoke a PL/SQL function that accepts a SSN value and returns the employees full name

  • Example3. Calling a PL/SQLFunction 2/5*package JavaAccessDB3StoredProc;

    import java.sql.*;import java.io.*;import oracle.jdbc.driver.*;

    public class JavaAccessDB3StoredProc {

    public static void main(String[] args) throws SQLException, ClassNotFoundException{/* -------------------------------------------------------------------------Calling a stored procedure/function from Java.The query string can be in Oracle format or standard JDBC callable syntax. 1. If you are using the Oracle syntax, the query string is:

    BEGIN ? := getName(?); END;

    2. If you are using the JDBC syntax, the query string is:

    { call ? := getName(?) }

    OUT parameter must be registered to be of type OracleTypes.CURSOR.You must use the method: getObject() to retrieve the result set.---------------------------------------------------------------------------*/Example3. Use the JDBC Thin Driver to invoke a PL/SQL function that accepts a SSN value and returns the employees full name

  • Example3. Calling a PL/SQLFunction 3/5* Connection conn = null; System.out.println("***Attempting to load Oracle thin driver"); // Load the Oracle JDBC driver Class.forName ("oracle.jdbc.OracleDriver"); System.out.println("***Driver manager created"); try { conn = DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:XE,"csuperson","euclid"); if (conn != null) { System.out.println("***Connection created for CSUPERSON/EUCLID ***"); } else { System.out.println("***No connection was created"); }

    String myQuery = " BEGIN ? := getName(?); END; "; CallableStatement stmt = conn.prepareCall(myQuery);

    // register the type of the OUT parameter using an Oracle specific type //Example: stmt.registerOutParameter(1, OracleTypes.CURSOR);

    stmt.registerOutParameter(1, OracleTypes.VARCHAR);

    Example3. Use the JDBC Thin Driver to invoke a PL/SQL function that accepts a SSN value and returns the employees full name

  • Example3. Calling a PL/SQLFunction 4/5*

    // set the IN parameterint SSN = 123456789;stmt.setInt(2, SSN);

    // execute statement and retrieve returned stringSystem.out.println("***Ready to call procedure.");

    stmt.execute();String empName = (String) stmt.getObject(1);

    // print the resultsSystem.out.println("***Emp name: " + empName);

    } //end try Example3. Use the JDBC Thin Driver to invoke a PL/SQL function that accepts a SSN value and returns the employees full name

  • Example3. Calling a PL/SQLFunction 5/5*catch (SQLException e) {System.out.println("Test threw a " + e.getClass() + "\n with message: " + e.getMessage() + " : Error code (" + e.getErrorCode() + ")" ); } // Clean up connection is there was one finally { if(conn != null) { conn.close(); System.out.println("***Connection closed"); } else { System.out.println("***There was no connection"); } } }}

    Example3. Use the JDBC Thin Driver to invoke a PL/SQL function that accepts a SSN value and returns the employees full name

  • Example4. Call PL/SQL Receive a ResultSet 0/5*This PL/SQL procedure accepts a Dept. No. and returns an Oracle cursor holding a list of employees :

    function getPeopleByDept ( theDnoNo in number ) return Sys_RefCursor as PeopleCursor sys_refCursor;begin open PeopleCursor for select SSN, Lname, Dno, Salary, Bdate from employee where (dno = theDnoNo); return PeopleCursor;end getpeoplebydept;Example4. Use the JDBC Thin Driver to invoke a PL/SQL stored procedure. The proc. accepts a dept nunmber and returns a list of employees on that dept.

  • Example4. Call PL/SQL Receive a ResultSet 1/5*package JavaAccessDB4StoredProcCursor; import java.sql.*; import java.io.*; import oracle.jdbc.driver.*; public class JavaAccessDB4StoredProcCursor {public static void main(String[] args) throws SQLException, ClassNotFoundException{/* ---------------------------------------------------------------------------Calling a stored procedure/function from Java.The query string can be in Oracle format or standard JDBC callable syntax. 1. If you are using the Oracle syntax, the query string is: BEGIN ? := getName(?); END;2. If you are using the JDBC syntax, the query string is: { call ? := getName(?) } OUT parameter must be registered to be of type OracleTypes.CURSOR.You must use the method: getObject() to retrieve the result set.-----------------------------------------------------------------------------*/Example4. Use the JDBC Thin Driver to invoke a PL/SQL stored procedure. The proc. accepts a dept nunmber and returns a list of employees on that dept.

  • Example4. Call PL/SQL Receive a ResultSet 1/5* Connection conn = null; System.out.println ("***Attempting to load Oracle thin driver"); // Load the Oracle JDBC driver Class.forName ("oracle.jdbc.OracleDriver"); System.out.println("***Driver manager created"); try { conn = DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:XE", "csuperson", "euclid"); if (conn != null) { System.out.println("Connection created for CSUPERSON/EUCLID"); } else { System.out.println("***No connection was created"); } String myQuery = " BEGIN ? := getPeopleByDept(?); END; "; CallableStatement stmt = conn.prepareCall(myQuery);

    Example4. Use the JDBC Thin Driver to invoke a PL/SQL stored procedure. The proc. accepts a dept nunmber and returns a list of employees on that dept.

  • Example4. Call PL/SQL Receive a ResultSet 1/5*

    // register type of the out param with Oracle specific typestmt.registerOutParameter(1, OracleTypes.CURSOR);

    // set the in paramint theDeptNo = 4;stmt.setInt(2, theDeptNo);

    // execute and retrieve the result setSystem.out.println("***Ready to call procedure.");stmt.execute();ResultSet rs = (ResultSet)stmt.getObject(1);

    // print the results: while (rs.next()) { System.out.println(rs.getString(1) + "\t" + rs.getString(2) + "\t" + rs.getInt(3) + "\t" + rs.getFloat(4) + "\t" + rs.getDate(5).toString());}Example4. Use the JDBC Thin Driver to invoke a PL/SQL stored procedure. The proc. accepts a dept nunmber and returns a list of employees on that dept.

  • Example4. Call PL/SQL Receive a ResultSet 1/5*catch (SQLException e) { System.out.println("Test threw a " + e.getClass() + "\n with message: " + e.getMessage() + " : Error code (" + e.getErrorCode() + ")" ); }

    // Clean up connection is there was onefinally { if(conn != null) { conn.close(); System.out.println("***Connection closed"); } else { System.out.println("***There was no connection"); }

    } }}

    Example4. Use the JDBC Thin Driver to invoke a PL/SQL stored procedure. The proc. accepts a dept nunmber and returns a list of employees on that dept.

  • Adding JDBC drivers to your program*

  • Example5: Updatable ResultSetpackage OracleJDBCDemo5.client;

    import java.sql.*;import oracle.jdbc.*;//update salary (increase by $1)public class OracleJDBCDemo5 {

    public static void main(String[] args) throws SQLException, ClassNotFoundException { System.out.print("Connecting to the database..."); try { // Load the Oracle JDBC driver Class.forName("oracle.jdbc.OracleDriver"); System.out.println("Driver manager created"); Connection conn = null; //you may replace "localhost" by "127.0.0.1" (or real TCP address) conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "csuperson", "euclid"); if (conn != null) { System.out.println("Connection created for CSUPERSON/EUCLID"); } else { System.out.println("***No connection was created"); return; }

    //Create a statement returning data for UPDATE Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE, ResultSet.CLOSE_CURSORS_AT_COMMIT); System.out.println("Updateble ResultSet was created"); ResultSet rset = stmt.executeQuery("select Salary, Fname from employee");

    while(rset.next()){ //modify the employee's salary (add $1 ) System.out.println("Name ==> " + rset.getString("Fname")); double oldSalary = rset.getDouble("Salary"); System.out.println("Old salary ==> " + oldSalary);

    double newSalary = oldSalary + 1; rset.updateDouble("Salary", newSalary); rset.updateRow(); System.out.println("New salary ==> " + newSalary); }

    // close the result set, the statement and connect rset.close(); stmt.close(); conn.close(); System.out.println("Adios."); } //end try catch (SQLException e) { System.out.println(e.getMessage()); } //end catch } //end main} //end class*

  • Example6. Prepared Statementpackage JavaAccessDB5PreparedStmt;import java.sql.*;public class JavaAccessDB5PreparedStmt {//-------------------------------------------------------------------//Using a Prepared Statement to retrieve female employees//-------------------------------------------------------------------public static void main(String[] args) {try {Class.forName("oracle.jdbc.OracleDriver");String url = "jdbc:oracle:thin:@sancho.csuohio.edu:1521:ORCL";String user = "CSUPERSON";String pwd = "EUCLID";

    Connection con = DriverManager.getConnection(url, user, pwd); String mySql = "select * from employee where sex = ? and dno = ?"; PreparedStatement stmt = con.prepareStatement(mySql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); //set gender value and department number stmt.setString(1, "F"); stmt.setInt(2, 4); stmt.setFetchSize(10); ResultSet rset = stmt.executeQuery();

    while (rset.next()){ System.out.println(rset.getInt("dno") + " " + rset.getString("fName")); }//end whileloop }catch (Exception e) {System.out.println(e);}

    }//end main

    }//end class

    *

  • References*JDBC 3.0 SUN Web Pagehttp://java.sun.com/javase/6/docs/technotes/guides/jdbc/Basic Tutorialhttp://java.sun.com/docs/books/tutorial/jdbc/basics/index.htmlAdvanced Tutorialhttp://java.sun.com/developer/Books/JDBCTutorial/index.htmlRowset Tutorialhttp://java.sun.com/j2se/1.5/pdf/jdbc-rowset-tutorial-1.5.0.pdfGetting Started with the JDBC APIhttp://java.sun.com/javase/6/docs/technotes/guides/jdbc/getstart/GettingStartedTOC.fm.htmlJDBC 4.0 Specification JSR 22, by Lance Andersen, Specification Lead. Sun Microsystems. November 7, 2006 November 2006 Final v1.0JDBCtm API Tutorial and Reference, Second Edition: Universal Data Access for the Javatm 2 Platform, published by Addison Wesley as part of the Java series, ISBN 0-201-43328-1. Wikipedia.com Page: JDBC, Consulted on 1-March-2008.

  • Appendix A. Creating a Trusted User for Logging on a SQL-Server*Log on the SQL-ServerClick on Security > LoginsRight-click on Logins, select New login

  • Appendix A. Creating a Trusted User for Logging on a SQL-Server*Enter Login name (csuperson)

    Select option: SQL Server Authentication

    Enter (confirm) Password (euclid)

    Uncheck option Enforce password policy

    Choose Default Database: Company

    Select (left top pane) option User Mapping

  • Appendix A. Creating a Trusted User for Logging on a SQL-Server*Under column Database check option for Company database

    Under Database Roles check the following options:db datareader, db datawriter, db ddladmin,db public.

    Click the OK button.

    The user: csuperson / euclid can now log into the SQL-server as a trusted user.

    Use the credentials provided by this user / password to setup a JDBC connection object.

  • Appendix A. Creating a Trusted User for Logging on a SQL-Server*Allow multiple login modes on the SQL server. Right-click on the topmost database icon (identifying the current connection. In this example CARIBE (SQL )

    Select Properties

  • Appendix A. Creating a Trusted User for Logging on a SQL-Server*Under Select a Page choose the entry labeled: Security.

    Make sure to select the option labeled: SQL Server and Windows Authentication mode.

    Click the OK button.

    You are ready to try Windows logon as well as Trusted User mode.