Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Entity–attribute–value model wikipedia , lookup
Extensible Storage Engine wikipedia , lookup
Oracle Database wikipedia , lookup
Microsoft Jet Database Engine wikipedia , lookup
Clusterpoint wikipedia , lookup
Microsoft SQL Server wikipedia , lookup
Database model wikipedia , lookup
Relational model wikipedia , lookup
http://www.csie.nctu.edu.tw/~tsaiwn/java/ Programming in Java JDBC/ODBC Java DataBase Access 蔡文能 交通大學資訊工程學系 [email protected] 交通大學資訊工程學系 Java JDBC Agenda Extend your JDK and JRE Introduction to ODBC and JDBC JDBC Drivers JDBC Statements Statement PreparedStatement CallableStatement ResultSet Transactions concept CORBA again 交通大學資訊工程學系 蔡文能 第2頁 Java JDBC Extend your JDK and JRE 把 所有 class 都壓縮到一個 .jar 檔案 (名稱隨意, 但不要與現有的重複) 例如: jar cvf myutilabc.jar M*.class So*.class (也可用 WINZIP 壓成 ZIP 檔再 rename 成 .jar 檔) 把壓好的 .jar 檔 copy 到 你 JDK 根目錄下的 \jre\lib\ext\ 即可 注意 .jar 檔中的目錄樹要與各 class 宣告的 package 相符合 就是說不可以欺騙 Java compiler 與 Interpreter (JVM) 可用 jar tvf your.jar 看看 (或用 WINZIP 看) 打 jar 看看 help 這樣 javac MyClass.java 編譯 或 java MyClass 執行就都不用指定classpath 若不是放 JDK 的 \jre\lib\ext\ 中, 則要指定 .jar 檔為你的 classpath javac -classpath ./mydir/myutil.jar; MyTest.java java -classpath ./mydir/myutil.jar; MyTest (注意 分號不能省; 可以多個 jar 檔用 ; 分開, 也可為目錄) 交通大學資訊工程學系 蔡文能 第3頁 Java JDBC Internet Technology RMI JDBC CORBA java.net TCP/IP Network 交通大學資訊工程學系 蔡文能 Copyright © 1997 Alex Chaffee 第4頁 Java JDBC Access to the DataBase Most popular form of database system is the Relational DataBase System. (invented by Dr. E.F.Codd) Examples: Oracle, Sybase, IBM DB2, MS Sequel Server, MS Access. (Informix 已在2001年被 IBM 併購) Structured Query Language (SQL) is used among relational databases to construct queries. These queries can be stand-alone or embedded within applications. This form of SQL is known as embedded SQL. 2001年7月2日,IBM公司順利完成斥資10億美元對Informix公司的資料庫 資產的收購。 IBM公司因此成為世界最大的中介軟體(MiddleWare)供應商 。 交通大學資訊工程學系 蔡文能 第5頁 Java JDBC Relational Databases 關聯式資料庫 Invented by Dr. E.F.Codd. data stored in records which live in tables Multiple tables. Each table is associated with a list of fields. Each field (column) has a name, and type. Each table is made up of a number of records (rows). Each row contains the values for each field. “Relation” (as in “Relational”) means row to column (not table to table) 列對欄位的關係; 注意不是表格對表格 ! 交通大學資訊工程學系 蔡文能 第6頁 Java JDBC Open DataBase Connectivity (ODBC) Standard ODBC (Open Database Connectivity) is a Microsoft standard from the mid 1990’s. ODBC standard is an interface by which application programs can access and process SQL databases in a DBMS-independent manner. It contains: A Data Source that is the database, its associated DBMS, operating system and network platform A DBMS Driver that is supplied by the DBMS vendor or independent software companies A Driver Manager that is supplied by the vendor of the O/S platform where the application is running. (例如MicroSoft提供Windows的) It requires an ODBC driver to be provided for each database system from which you want to manipulate data. 交通大學資訊工程學系 蔡文能 第7頁 Java JDBC ODBC Application Architecture Application Class1 Class2 ODBC Driver Manager DriverType1 DataSource1 交通大學資訊工程學系 蔡文能 DriverType2 DriverType3 DataSource2 DataSource3 第8頁 Java JDBC Java Support for ODBC : JDBC When applications written in Java want to access data sources, they use classes and associated methods provided by Java DBC (JDBC) API. JDBC is specified an an “interface”. An interface in Java can have many “implementations”. So it provides a convenient way to realize many “drivers” JDBC is implemented via classes in the java.sql package 交通大學資訊工程學系 蔡文能 第9頁 Java JDBC Java Support for embedded SQL Java supports embedded SQL. Also it provides an JDBC API as a standard way to connect to common relational databases. You need a JDBC:ODBC bridge for using the embedded SQL in Java. Other JDBC Drivers are available for some RDBMS java.sql package and an extensive exception hierarchy. 交通大學資訊工程學系 蔡文能 第10頁 Java JDBC SQL SQL was initiated by IBM as part of its System R research prototype in the late 1970s There are many different types of SQL commands (SELECT, INSERT, UPDATE, DELETE, …). For example: to create a new record: "INSERT INTO password (Name, Password) VALUES ('Dave', 'blah')" Reference: A guide to SQL standard – 4th Edition. CJ Date & Hugh Darman. Addison Wesley. 1997. http://www.opengroup.org/public/tech/datam/sql.htm 交通大學資訊工程學系 蔡文能 第11頁 Java JDBC General SELECT statement SELECT column1, column2, ..., columnN FROM table1 [, table2, ..., tableN ] [WHERE clause] column# are the field names. table# are table names. The WHERE clause can restrict the rows used to determine the result. 交通大學資訊工程學系 蔡文能 第12頁 Java JDBC Some other SQL Statements INSERT INTO table ( field1, field2 ) VALUES ( value1, value2 ) inserts a new record into the named table UPDATE table SET ( field1 = value1, field2 = value2 ) WHERE condition changes an existing record or records DELETE FROM table WHERE condition removes all records that match condition 交通大學資訊工程學系 蔡文能 Copyright © 1997 Alex Chaffee 第13頁 Java JDBC Embedded SQL Direct SQL (= ad-hoc SQL) is rarely used Also know as interactive SQL (iSQL) In practice: SQL is embedded in some application code user interaction, devices, programming logic SQL code is enbedded using special syntax into a host language (C, Java, etc.) 交通大學資訊工程學系 蔡文能 第14頁 Java JDBC JDBC JDBC Java DataBase Connectivity 交通大學資訊工程學系 蔡文能 第15頁 Java JDBC Side View of a Distributed Application Client E.g. a Java Applet Middle Ware Middle Ware IDL Server E.g. DBMS IDL Network Internet (TCP/IP) IDL = Interface Definition Language 交通大學資訊工程學系 蔡文能 第16頁 Java JDBC JDBC Components Driver Manager: Loads database drivers, and manages the connection between application & driver. Driver: Translates API calls to operations for a specific data source. Connection: A session between an application and a driver. Statement: A SQL statement to perform a query or an update operation. Metadata: Information about the returned data, driver and the database. Result Set : Logical set of columns and rows returned by executing a statement. 交通大學資訊工程學系 蔡文能 第17頁 Java JDBC JDBC Classes (java.sql.*) Java supports DB facilities by providing classes and interfaces for its components DriverManager class Connection interface (abstract class) Statement interface (to be instantiated with values from the actual SQL statement) ResultSet interface ResultSet = the records returned from a SQL Statement JDBC is implemented via classes in the java.sql package 交通大學資訊工程學系 蔡文能 第18頁 Java 交通大學資訊工程學系 蔡文能 JDBC 第19頁 Java JDBC JDBC Class Diagram 交通大學資訊工程學系 蔡文能 Copyright © 1997 Alex Chaffee 第20頁 Java JDBC Running a JDBC Application Phase Initialisation Processing Termination 交通大學資訊工程學系 蔡文能 Task Relevant java.sql classes Load driver Create connection DriverManager Connection Generate SQL statements Process result data Statement ResultSet etc. Terminate connection Release data structures Connection Statement etc. 第21頁 Java JDBC JDBC PseudoCode All JDBC programs do the following: 1) load the JDBC driver 2) Specify the name and location of the database being used 3) Connect to the database with a Connection object 4) Execute a SQL query using a Statement object 5) Get the results in a ResultSet object 6) Finish by closing the ResultSet, Statement and Connection objects 交通大學資訊工程學系 蔡文能 Continued 第22頁 Java JDBC JDBC Application Architecture Application Connection Statement ResultSet Driver Manager Driver DataSource 交通大學資訊工程學系 蔡文能 Driver Driver DataSource DataSource 第23頁 Java JDBC A Simple JDBC application loadDriver getConnection createStatement execute(SQL) Result handling yes More results ? no closeStatment closeConnection import java.sql.*; public class jdbctest { public static void main(String args[]){ try{ Class.forName("org.postgresql.Driver"); Connection con = DriverManager.getConnection ("jdbc:postgresql://lsir-cis-pc8:5401/pcmdb", "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) { System.err.println(e); }}} 交通大學資訊工程學系 蔡文能 第24頁 Java JDBC Driver Manager Class Provides static, “factory” methods for creating objects implementing the connection interface. Factory methods create objects on demand when a connection is needed to a DB driver, DriverManager does it using its factory methods. E.g.: Connection foo = DriverManager.getConnection(DBURL); java.sql.Connection interface corresponds to a session (a connection with a specific database). 交通大學資訊工程學系 蔡文能 第25頁 Java JDBC JDBC Drivers JDBC-ODBC Bridge. 2) A native API partly Java Technology enabled driver. 3) A net protocol driver (through Middleware). 4) A fully Java Technology enabled driver direct built into DB engine. Type I ODBC ODBC “Bridge” Driver Type II CLI (.lib) “Native” JDBC Type III Middleware “Middleware” Server Type IV “Pure” 1) 交通大學資訊工程學系 蔡文能 第26頁 Java JDBC Type I Drivers Use bridging technology Requires installation/configuration on client machines Not good for Web / Applet e.g. ODBC Bridge sun.jdbc.odbc.JdbcOdbcDriver 交通大學資訊工程學系 蔡文能 Copyright © 1997 Alex Chaffee 第27頁 Java JDBC Type II Drivers Native API drivers Requires installation/configuration on client machines Used to leverage existing CLI libraries Usually not thread-safe Mostly obsolete now e.g. Intersolv Oracle Driver, WebLogic drivers 交通大學資訊工程學系 蔡文能 Copyright © 1997 Alex Chaffee 第28頁 Java JDBC Type III Drivers Calls middleware server, usually on database host Very flexible -- allows access to multiple databases using one driver Only need to download one driver But it’s another server application to install and maintain e.g. Symantec DBAnywhere 交通大學資訊工程學系 蔡文能 Copyright © 1997 Alex Chaffee 第29頁 Java JDBC Type IV Drivers 100% Pure Java -- the Holy Grail Use Java networking libraries to talk directly to database engines Only disadvantage: need to download a new driver for each database engine e.g. Oracle, mSQL 交通大學資訊工程學系 蔡文能 Copyright © 1997 Alex Chaffee 第30頁 Java JDBC Where to get JDBC Drivers There are a number of JDBC drivers available. (more than 200 ) Information on installing them is available at : http://industry.java.sun.com/products/jdbc/drivers http://developers.sun.com/product/jdbc/drivers/ 交通大學資訊工程學系 蔡文能 第31頁 Java 交通大學資訊工程學系 蔡文能 JDBC 第32頁 Java JDBC Using JDBC Drivers Loading a driver Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver” ); OR DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver( ) ); Making a Connection String url = “jdbc:oracle:oci8:@mydb”; Connection con = DriverManager.getConnection(url, “mylogin”, “password”); url identifies the Data Source in Database. See next Slide. 交通大學資訊工程學系 蔡文能 第33頁 Java JDBC Implicit Driver Loading Setting system property: jdbc.drivers A colon-separated list of driver classnames. Can be set when starting the application java -Djdbc.drivers=org.postgresql.Driver application Can also be set from within the Java application Properties prp = System.getProperties(); prp.put("jdbc.drivers" "com.mimer.jdbc.Driver:org.postgresql.Driver"); System.setProperties(prp); The DriverManager class attempts to load all the classes specified in jdbc.drivers when the DriverManager class is initialized. 交通大學資訊工程學系 蔡文能 第34頁 Java JDBC JDBC Database URL (1/2) Format: jdbc:subprotocol:source each driver has its own subprotocol each subprotocol has its own syntax for the source jdbc:odbc:DataSource e.g. jdbc:odbc:NCTUDB jdbc:msql://host[:port]/database e.g. jdbc:msql://foo.nctu.edu.tw:3388/sampledb 交通大學資訊工程學系 蔡文能 Copyright © 1997 Alex Chaffee 第35頁 Java JDBC JDBC Database URL (2/2) jdbc:odbc: //host.domain.com: 2048 /data/file The comms protocol The machine holding the database. The port used for the connection. The path to the database on the machine e.g. jdbc:odbc:nctuDB 交通大學資訊工程學系 蔡文能 第36頁 Java JDBC Another Example using IBM DB2 url identifies the Data Source in Database. See previous Slide. // register the driver with DriverManager Class.forName("COM.ibm.db2.jdbc.app.DB2Driver"); String url = "jdbc:db2:DATABASE_NAME"; Connection con =DriverManager.getConnection(url, "USERNAME", "PASSWORD"); 交通大學資訊工程學系 蔡文能 第37頁 Java JDBC JDBC Statements A JDBC statement object is used to send your SQL statement to the database server A JDBC statement is associated with an open connection and not any single SQL statement JDBC provides three classes of SQL statement Statement PreparedStatement CallableStatement 交通大學資訊工程學系 蔡文能 第38頁 Java JDBC JDBC Programming Steps Import necessary packages; Ex: import java.sql.*; Load JDBC driver(driver should have been installed) Data source and its location should have been registered. Allocate Connection object, Statement object and ResultSet object Execute query using Statement object Retrieve data from ResultSet object Close Connection object. 交通大學資訊工程學系 蔡文能 第39頁 Java JDBC Obtaining JDBC drivers Usually provided (free) by DataBase vendors Common ones oracle.jdbc.driver.OracleDriver com.mysql.jdbc.Driver sun.jdbc.odbc.JdbcOdbcDriver Need to download and install In a webapp, put the Jar file in WEB-INF/lib 交通大學資訊工程學系 蔡文能 第40頁 Java JDBC Connecting to a Database Via a DriverManager (old) Class.forName(DriverClassName).newInstance(); Connection con = DriverManager.getConnection(URL,Username,Password); Via a DataSource (new) Create DataSource object in configuration (e.g. in Tomcat’s context.xml file) 交通大學資訊工程學系 蔡文能 第41頁 Java JDBC Creating JDBC Statement // con is a Connection to a DB Statement stmt = con.createStatement(); String createINTROCS = “Create table INTROCS “+ “(SSN Integer not null, Name VARCHAR(32), “+ “Marks Integer)”; stmt.executeUpdate(createINTROCS); String insertMYCS = “Insert into INTROCS values “+ “(123456789, abc, 100)”; stmt.executeUpdate(insertMYCS); 交通大學資訊工程學系 蔡文能 第42頁 Java JDBC ResultSet A ResultSet is returned when you execute an SQL statement: // stmt is a Statement created via creatStatement( ) ResultSet rs = stmt.executeQuery("SELECT * FROM password"); A ResultSet object is similar to a ‘table’ of answers, which can be examined by moving a ‘pointer’ (cursor). ResultSet can be used to store the query result 交通大學資訊工程學系 蔡文能 第43頁 Java JDBC Processing the ResultSet ResultSet can be used to store the query result The ResultSet class contains many methods for accessing the value of a column of the current row can use the column name or position e.g. get the value in the lastName column: rs.getString("lastName") The ‘tricky’ aspect is that the values are SQL data, and so must be converted to Java types/objects. There are many methods for accessing/converting the data, e.g. getString(), getDate(), getInt(), getFloat(), getObject() 交通大學資訊工程學系 蔡文能 第44頁 Java JDBC Impedance Mismatch Example: SQL in Java: Java uses int, char[..], objects, etc SQL uses tables Impedance mismatch = incompatible types Why not use only one language? SQL cannot do everything that the host language can do Solution: use cursors 交通大學資訊工程學系 蔡文能 第45頁 Java JDBC Moving the DataBase Cursor cursor 23 5 John Mark 17 98 Paul Peter Cursor operations: first(), last(), next(), previous(), etc. Typical code: String queryINTROCS = “select * from INTROCS”; ResultSet rs = Stmt.executeQuery(queryINTROCS); While (rs.next( )) { int ssn = rs.getInt(“SSN”); String name = rs.getString(“NAME”); int marks = rs.getInt(“MARKS”); } 交通大學資訊工程學系 蔡文能 Note: column number can also be used in place of column name. Refer to java.sql.ResulSet API for more details 第46頁 Java JDBC More on DataBase Cursors Cursors can also modify a relation rset.updateString("script", "ebay"); rset.updateRow( ); // updates the row in the data source The cursor can be a scrolling one: can go forward, backward first(), last(), next(), previous(), absolute(5) We can determine the order in which the cursor will get tuples by the ORDER BY clause in the SQL query 交通大學資訊工程學系 蔡文能 第47頁 Java JDBC isNull In SQL, NULL means the field is empty Not the same as 0 or "" (空字串) In JDBC, you must explicitly ask if a field is null by calling ResultSet.isNull(column_name) 交通大學資訊工程學系 蔡文能 Copyright © 1997 Alex Chaffee 第48頁 Java JDBC Dynamic JDBC Statements Variables within SQL statement Precompiled once, multiple executions PreparedStatement for invocation PreparedStatement stmt = con.prepareStatement ( "SELECT * FROM data WHERE date = ?"); stmt.setDate (1, j_date); ResultSet rset = stmt.executeQuery(); 交通大學資訊工程學系 蔡文能 第49頁 Java JDBC Prepared Statement (1/2) Unlike “Statement,” it is given a SQL statement when it is created. Used when you want to execute “Statement” object many times E.g String insert = “Insert into INTROCS (?,?,?)”; PreparedStatement stmt2 = con.prepareStatement(insert); //… stmt2.setInt(1,123456789); stmt2.setString(2, “abc”); stmt2.setInt(3,100); stmt2.executeUpdate( ); 交通大學資訊工程學系 蔡文能 第50頁 Java JDBC Prepared Statement (2/2) Executing Select Statement E.g String query =“SELECT Name from INTROCS where SSN=?”; PreparedStatement stmt2 = con.prepareStatement(query); stmt2.setInt(1, mySSN); ResultSet rs = stmt2.executeQuery( ); While (rs.next( ) ) System.out.println(rs.getString(Name); You may extract individual columns, rows or cell from the ResultSet using the metadata. 交通大學資訊工程學系 蔡文能 第51頁 Java JDBC Callable Statement Used for executing stored procedures Example String createProcedure = “Create Procedure ShowGoodStudents” + “as Select Name from INTROCS where Marks >= 90)”; Stmt.executeUpdate(createProcedure); CallableStatement cs = con.prepareCall(“(call ShowGoodStudents)”); ResultSet rs = cs.executeQuery( ); 交通大學資訊工程學系 蔡文能 第52頁 Java JDBC ResultSet Meta Data (1/3) Meta data is the information about the database Stores the number, types and properties of ResultSet’s columns. // rs is a ResultSet ResultSetMetaData rsm = rs.getMetaData(); int number = rsm.getColumnCount(); for (int i=0; i< number;i++) System.out.println(rsm.getColumnName(i)); You may extract individual columns, rows or cell from the ResultSet using the metadata. 交通大學資訊工程學系 蔡文能 第53頁 Java JDBC ResultSet Meta Data (2/3) Meta data example ID 007 008 Name James Bond Aj. Andrew 交通大學資訊工程學系 蔡文能 Course Shooting Kung Fu Mark meta data 99 1 第54頁 Java JDBC ResultSet Meta Data (3/3) What's the number of columns in the ResultSet? What's a column's name? What's a column's SQL type? What's the column's normal max width in chars? What's the suggested column title for use in printouts and displays? What's a column's number of decimal digits? Does a column's case matter? Is the column a cash value? Will a write on the column definitely succeed? Can you put a NULL in this column? Is a column definitely not writable? Can the column be used in a where clause? Is the column a signed number? Is it possible for a write on the column to succeed? …, and so on... 交通大學資訊工程學系 蔡文能 Copyright © 1997 Alex Chaffee 第55頁 Java JDBC DatabaseMetaData // con is a Connection DatabaseMetaData dbm = con.getMetaData(); What tables are available? What's our user name as known to the database? Is the database in read-only mode? If table correlation names are supported, are they restricted to be different from the names of the tables? and so on… 交通大學資訊工程學系 蔡文能 Copyright © 1997 Alex Chaffee 第56頁 Java JDBC Using Meta Data // rs is a ResultSet ResultSetMetaData md = rs.getMetaData(); int numCols = md.getColumnCount(); for (int i = 0; i <= numCols; i++) { if (md.getColumnType(i) == Types.CHAR) System.out.println( md.getColumnName(i) ) } 交通大學資訊工程學系 蔡文能 第57頁 Java JDBC More Meta Data Methods getTableName() getPrecision() number of decimal digits in the column isSigned() returns true if column has signed numbers isCurrency() etc. 交通大學資訊工程學系 蔡文能 第58頁 Java JDBC Another Example of using Meta Data ResultSet rset = stmt.executeQuery(“SELECT * FROM data”); ResultSetMetaData rsmeta = rset.getMetaData(); int numCols = rsmeta.getColumnCount(); for (int i=1; i<=numCols; i++) { int ct = rsmeta.getColumnType(i); String cn = rsmeta.getColumnName(i); String ctn = rsmeta.getColumnTypeName(i); System.out.println(“Column #” + i + “: “ + cn + “ of type “ + ctn + “ (JDBC type: “ + ct + “)”); } 交通大學資訊工程學系 蔡文能 第59頁 Java JDBC Matching Java and SQL Data Types SQL Type BIT CHAR VARCHAR DOUBLE FLOAT INTEGER REAL DATE TIME TIMESTAMP Java class Boolean String String Double Double Integer Double java.sql.Date java.sql.Time java.sql.TimeStamp 交通大學資訊工程學系 蔡文能 ResultSet get method getBoolean() getString() getString() getDouble() getDouble() getInt() getFloat() getDate() getTime() getTimestamp() 第60頁 Java JDBC Example: simpJDBC.java (1/4) // simpJDBC.java // Displays the firstnames and lastnames // of the Authors table in the Books db. import java.sql.*; public class simpJDBC { public static void main(String[] args) { // The URL for the Books database. // ’Protected' by a login and password. String url = "jdbc:odbc:Books"; String username = "anonymous"; String password = "guest"; : 交通大學資訊工程學系 蔡文能 第61頁 Java JDBC Example: simpJDBC.java (2/4) try { // load the JDBC-ODBC Bridge driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // connect to db using DriverManager Connection conn = DriverManager.getConnection( url, username, password ); // Create a statement object Statement statement = conn.createStatement(); // Execute the SQL query ResultSet rs = statement.executeQuery( "SELECT lastName, firstName FROM Authors" ); : 交通大學資訊工程學系 蔡文能 第62頁 Java JDBC Example: simpJDBC.java (3/4) // Print the result set while( rs.next() ) System.out.println( rs.getString("lastName") + ", " + rs.getString("firstName") ); // Close down statement.close(); conn.close(); } : 交通大學資訊工程學系 蔡文能 第63頁 Java JDBC Example: simpJDBC.java (4/4) catch ( ClassNotFoundException cnfex ) { System.err.println( "Failed to load JDBC/ODBC driver." ); cnfex.printStackTrace(); System.exit( 1 ); // terminate program } catch ( SQLException sqlex ) { System.err.println( sqlex ); sqlex.printStackTrace(); } } // end of main() } // end of simpJDBC class 交通大學資訊工程學系 蔡文能 第64頁 Java JDBC Output of simpJDBC.java 交通大學資訊工程學系 蔡文能 第65頁 Java JDBC Transactions concept Transaction = more than one statement which must all succeed (or all fail) together If one fails, the system must reverse all previous actions Also can’t leave DB in inconsistent state halfway through a transaction COMMIT = complete transaction ROLLBACK = abort 交通大學資訊工程學系 蔡文能 Copyright © 1997 Alex Chaffee 第66頁 Java JDBC Transactions and JDBC (1/2) JDBC allows SQL statements to be grouped together into a single transaction Transaction control is performed by the Connection object, default mode is auto-commit, I.e., each sql statement is treated as a transaction We can turn off the auto-commit mode with con.setAutoCommit(false); And turn it back on with con.setAutoCommit(true); Once auto-commit is off, no SQL statement will be committed until an explicit is invoked con.commit( ); At this point all changes done by the SQL statements will be made permanent in the database. 交通大學資訊工程學系 蔡文能 第67頁 Java JDBC Transactions and JDBC (2/2) If we don’t want certain changes to be made permanent, we can issue con.rollback(); Any changes made since the last commit will be ignored – usually rollback is used in combination with Java’s exception handling ability to recover from unpredictable errors. Example: // con is a Connection con.setAutocommit(false); Statement stmt = con.createStatement( ); stmt.executeUpdate(“INSERT INTO INTROCS VALUES (1234,’John’,0)”); con.rollback( ); stmt.executeUpdate(“INSERT INTO INTROCS VALUES (1234,’John’,0)”); con.commit( ); con.setAutoCommit(true); 交通大學資訊工程學系 蔡文能 第68頁 Java JDBC Error Handling Each SQL statement can generate errors Thus each SQL method should be put into a try-block Exceptions are reported through exceptions of class SQLException 交通大學資訊工程學系 蔡文能 第69頁 Java JDBC Handling Errors with Exceptions Programs should recover and leave the database in a consistent state. In Java statements which are expected to “throw” an exception or a warning are enclosed in a try block. If a statement in the try block throws an exception or warning, it can be caught in one of the corresponding catch statements Example: // stmt is a statement try{ stmt.executeUpdate(queryINTROCS); } catch (SQLException e){ System.out.println(e.getMessage( )) } 交通大學資訊工程學系 蔡文能 第70頁 Java JDBC Java Example using JDBC (1/3) import java.sql.*; import oracle.jdbc.driver.*; import oracle.sql.*; import java.math.BigDecimal; import java.util.Map; import java.io.*; class employee { public static void main (String args []) throws SQLException, IOException { String user, pass, snum, namer; int enumber; user = readEntry("userid : "); pass = readEntry("password: "); // Connect DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver ()); OracleConnection conn = (OracleConnection) DriverManager.getConnection("jdbc:oracle:oci8:@ccdb", user,pass); 交通大學資訊工程學系 蔡文能 第71頁 Java JDBC Java Example using JDBC (2/3) Statement stmt = conn.createStatement (); ResultSet rset = stmt.executeQuery ("select distinct eno,ename,zip,hdate from employees"); while (rset.next ()) { namer = rset.getString(2); if ( !rset.wasNull() ) { System.out.println(rset.getInt(1) + " " + namer + " " + rset.getInt(3) + " " + rset.getDate(4)); } } System.out.println(); conn.close(); } 交通大學資訊工程學系 蔡文能 第72頁 Java JDBC Java Example using JDBC (3/3) //readEntry function -- to read input string static String readEntry(String prompt) { try { StringBuffer buffer = new StringBuffer(); System.out.print(prompt); System.out.flush(); int c = System.in.read(); while(c != '\n' && c != -1) { buffer.append((char)c); c = System.in.read(); } return buffer.toString().trim(); } catch (IOException e) { return ""; } } } 交通大學資訊工程學系 蔡文能 第73頁 Java JDBC More ResultSet Methods (1/4) boolean next() activates the next row the first call to next() activates the first row returns false if there are no more rows void close() disposes of the ResultSet allows you to re-use the Statement that created it automatically called by most Statement methods 交通大學資訊工程學系 蔡文能 Copyright © 1997 Alex Chaffee 第74頁 Java JDBC More ResultSet Methods (2/4) Type getType(int columnIndex) returns the given field as the given type fields indexed starting at 1 (not 0) Type getType(String columnName) same, but uses name of field less efficient int findColumn(String columnName) looks up column index given column name 交通大學資訊工程學系 蔡文能 Copyright © 1997 Alex Chaffee 第75頁 Java JDBC More ResultSet Methods (3/4) String getString(int columnIndex) boolean getBoolean(int columnIndex) byte getByte(int columnIndex) short getShort(int columnIndex) int getInt(int columnIndex) long getLong(int columnIndex) float getFloat(int columnIndex) double getDouble(int columnIndex) Date getDate(int columnIndex) Time getTime(int columnIndex) Timestamp getTimestamp(int columnIndex) 交通大學資訊工程學系 蔡文能 Copyright © 1997 Alex Chaffee 第76頁 Java JDBC More ResultSet Methods (4/4) String getString(String columnName) boolean getBoolean(String columnName) byte getByte(String columnName) short getShort(String columnName) int getInt(String columnName) long getLong(String columnName) float getFloat(String columnName) double getDouble(String columnName) Date getDate(String columnName) Time getTime(String columnName) Timestamp getTimestamp(String columnName) 交通大學資訊工程學系 蔡文能 Copyright © 1997 Alex Chaffee 第77頁 Java JDBC JDBC Reference Reference: http://java.sun.com/products/jdbc/ http://developer.java.sun.com/developer/onlineTraining/ Database/JDBC20Intro/ 交通大學資訊工程學系 蔡文能 第78頁 Java JDBC http://java.sun.com/products/jdbc/ 交通大學資訊工程學系 蔡文能 第79頁 Java JDBC More than RMI CORBA Common Object Request Broker Architecture http://www.corba.org/ OMG http://www.omg.org/ J2EE (Sun) J2EE Tutorial: http://java.sun.com/j2ee/1.4/docs/tutorial/doc/ ASP.Net (Microsoft) 交通大學資訊工程學系 蔡文能 第80頁 Java JDBC What is CORBA? Common Object Request Broker Architecture Defines a family of open software interface specifications for distributed object computing. http://www.omg.org Inside every Java Runtime Environment. Commonly used in middle tier and backend (e.g. database) connections. Open Source and Commercial Implementations Available Usually buried deep inside the software Difficult or impossible to tell when it is being used 交通大學資訊工程學系 蔡文能 第81頁 Java JDBC What is Distributed Object Computing? Extends the benefits of object-oriented technology across process and machine boundaries to encompass entire networks. Attempts to make remote objects appear to programmers as if they were local objects in the same process. This is called location transparency. 交通大學資訊工程學系 蔡文能 第82頁 Java JDBC CORBA Independence Open Standard for Distributed Object Oriented Design Independent of Hardware Platform Independent of Operating System Independent of Programming Language Independent of Object Location http://www.omg.org OMG = Object Management Group Consortium of 800+ companies founded in 1989. 交通大學資訊工程學系 蔡文能 第83頁 Java JDBC Object Request Broker (ORB) 1/2 ORBs mediate between objects and things that use them (clients) IDL Client Object IDL Object Request Broker IDL = Interface Definition Language 交通大學資訊工程學系 蔡文能 第84頁 Java JDBC Object Request Broker (ORB) 2/2 The glue that binds parts together is the ORB The Interface to an object can be distributed over a network Shape of boundary is defined in IDL IDL = Interface Definition Language 交通大學資訊工程學系 蔡文能 第85頁 Java JDBC ORBs: Medium for Integration C C++ Perl Delphi ORB Ada Java ORB CORBA / IIOP—Internet Inter-ORB Protocol ORB Application 交通大學資訊工程學系 蔡文能 ActiveX 第86頁 Java JDBC IIOP—Internet Inter-ORB Protocol IIOP The Internet Inter-ORB Protocol, defined in the Spec as a vendor-independent, wire-level network protocol on top of TCP/IP. This allows ORB implementations of different vendors to interoperate. 交通大學資訊工程學系 蔡文能 第87頁 Java JDBC JDBC: Use DBMS in Java 謝謝捧場 http://www.csie.nctu.edu.tw/~tsaiwn/java/ 蔡文能 交通大學資訊工程學系 蔡文能 第88頁