UFCE4Y UFCE4Y-20-3 Components and Services Julia Dawson
UFCE4Y JDBC Java Database Connectivity
UFCE4Y What is JDBC Java Database Connectivity (JDBC) is an API for the Java programming language that defines how a client may access a database. Java Database Connectivity (JDBC) is an API for the Java programming language that defines how a client may access a database.API Java programming languagedatabaseAPI Java programming languagedatabase It provides methods for querying and updating data in a database. It provides methods for querying and updating data in a database. JDBC is oriented towards relational databases. JDBC is oriented towards relational databases.relational databasesrelational databases The Java Platform, Standard Edition includes the JDBC API together with an ODBC implementation of the API enabling connections to any relational database that supports ODBC. Java Platform, Standard EditionODBC Java Platform, Standard EditionODBC This driver is native code and not Java. This driver is native code and not Java.native codenative codehttp://en.wikipedia.org/wiki/JDBC
UFCE4Y Middleware Middleware is computer software that connects software components or applications. Middleware is computer software that connects software components or applications. It is used most often to support complex, distributed applications. It is used most often to support complex, distributed applications. It includes web servers, application servers, content management systems, and similar tools that support application development and delivery. It includes web servers, application servers, content management systems, and similar tools that support application development and delivery. Middleware is especially integral to modern information technology based on XML, SOAP, Web services, and service-oriented architecture. Middleware is especially integral to modern information technology based on XML, SOAP, Web services, and service-oriented architecture.
UFCE4Y RDBMS Relational Database Management System Database is under the control of a DBA Database is under the control of a DBA Application logic is isolated from data Application logic is isolated from data Many views from same data Many views from same data Computing power distributed Computing power distributed > 90% of VB applications are DB access
UFCE4Y Client Server Model RDBMS SQL Oracle Files Code Cobol Code RDBMS SQL VB & Oracle GUI HTML RDBMS SQL Browser, Java & Oracle Code GUI
UFCE4Y DB Access Objectives Database Vendor Independent Database Vendor Independent Not bound to a supplier Database Technology Independent Database Technology Independent Use X/Open SQL Call Level Interface Use X/Open SQL Call Level Interface Medium Level Interface Medium Level Interface Without support for full SQL/Java mapping Without support for full SQL/Java mapping Hardware Platform Independent Hardware Platform Independent Compiled code can run on other platforms Compiled code can run on other platforms
UFCE4Y JDBC Structure Java Application JDBC Manager JDBC Bridge Database Vendor Tech.Java & NativeJava - ProtocolJava – Net
UFCE4Y JDBC 1.0 Classes (1) java.sql.* DriverManager DriverManager The basic service for managing a set of JDBC drivers. When the method getConnection is called, the DriverManager will attempt to locate a suitable driver The basic service for managing a set of JDBC drivers. When the method getConnection is called, the DriverManager will attempt to locate a suitable driver Connection Connection A connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection. A connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection.
UFCE4Y JDBC 1.0 Classes (2) java.sql.* Statement Statement The object used for executing a static SQL statement and returning the results it produces. The object used for executing a static SQL statement and returning the results it produces. ResultSet ResultSet A table of data representing a database result set, which is usually generated by executing a statement that queries the database. A table of data representing a database result set, which is usually generated by executing a statement that queries the database. A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row.
UFCE4Y Summary JDBC is a simple way to access a DB JDBC is a simple way to access a DB JDBC programs are portable JDBC programs are portable JDBC programs are not vendor specific JDBC programs are not vendor specific The GUI can be separated from the DB code The GUI can be separated from the DB code Component use encourages separate location for the DB server, application code and the GUI Component use encourages separate location for the DB server, application code and the GUI
UFCE4Y Building a DB Saved as student.mdb
UFCE4Y Add ODBC
UFCE4Y import java.sql.*; public class DBStudent { public static void main(String[ ] args) { Connection con; Statement st; ResultSet rs; String query = "select * from students"; try { // Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:class", "", ""); st = con.createStatement(); rs = st.executeQuery(query); while (rs.next()) { System.out.println(rs.getString(2) + ":" + s.getString(3)); } rs.close(); st.close(); con.close(); } catch (Exception e) { System.err.println("Trouble at mill..." +e); } } //main } //class Example
UFCE4Y Example Code (1) import java.sql.*; public class DBStudent { public static void main(String[] args) { Connection con; Statement st; ResultSet rs; String query = "select * from students"; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:class", "", ""); st = con.createStatement(); rs = st.executeQuery(query); Run Query and get pointer/cursor to results Make Connection to ODBC database called class Add Driver to Driver List Locate SQL classes
UFCE4Y Example Code (2) while (rs.next( ) ) { System.out.println( rs.getString(2) +" : "+ rs.getString(3) ) ; } rs.close( ); st.close( ); con.close( ); } catch ( Exception e ) { System.err.println("Trouble at mill..." + e ); } } //main } //class Iterate (move cursor) over ResultSet Releases object's database and JDBC resources immediately Get column contents Jane:Brown Jo:Bloggs Sophie:Smith OUTPUT
UFCE4Y Connecting.... The driver must be registered with the JDBC DriverManager Load the driver class using : Class.forName() try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Class.forName("com.oracle.jdbc.OracleDriver"); } catch (ClassNotFoundException e) { /* Do exception stuff.. */} Can load database drivers dynamically!
UFCE4Y JDBC URLs The JDBC Driver use a JDBC URL to identify and connect to particular database. Eg: jdbc.odbc.studb jdbc.hsql:c/temp/appleDB jdbc.hsql. Each driver is able to recognises it's own URLs
UFCE4Y Making the Connection Connection con = DriverManager.getConnection( "url", "user", "password"); User and password may be blank for some databases Registered drivers are quizzed to see if they recognise the url Url, user and password can be obtained from (for example): a properties file a Servlet init() method an HTML form Always explicitly close the connection after use - otherwise others processes may be blocked from connecting.
UFCE4Y SQL Statements (3 types) Statement A basic SQL statement PreparedStatement A precompiled SQL statement - can improve efficiency (eg. repeat INSERT) CallableStatement To access procedures within the stored database (eg. PL/SQL)
UFCE4Y Statement Get a statement object for the connection thus: Statement stmt = con.createStatement(); Now perform an SQL statement and get the result like this: ResultSet rs = stmt.executeQuery("select * from names"); If a statement should return no result (eg. UPDATE or DELETE) Get the number of rows affected (for example): int count = stmt.executeUpdate("update from names where...."); See also execute() NOTE: These calls will close any other ResultSet associated with this Statement.
UFCE4Y Processing ResultSet Statement st = con.createStatement(); ResultSet rs = st.executeQuery( "select id, name, phone from company"); while (rs.next()) { System.out.print("Id is " + rs.getString("ID") + ", Name is " + rs.getString("Name") + ", Phone is " + rs.getString("PHONE"); } //while rs.close(); st.close(); NOTE: Column name is case insensitive Could also get columns by position (starting at 1). System.out.print("Id is " + rs.getString(1)
UFCE4Y SQL Data types Java types SQL typeJava Type getXXX() CHAR, VARCHAR... String getString() NUMERIC, DECIMALjava.Math.BigDecimal getBigDecimal() BITbooleangetBoolean() INTEGERintgetInt() FLOAT, DOUBLEdouble getDouble() BINARYbyte [ ] getBytes() DATEjava.sql.Date getDate() TIMEjava.sql.TimegetTime() NOTE: Not all drivers honour these. The getString() method returns a String representation of most of types.
UFCE4Y Beware of Nulls (Empty fields) If a column has null (empty) values - unpredictable results can occur. Best to trap these - first getXXX() the value and then test for null using wasNull() int amount = rs.getInt("STOCK"); if (rs.wasNull()) { System.out.print("Null"); } else { System.out.print(amount); }
UFCE4Y ResultSetMetaData Gives information about the structure of a particular ResultSet: number of columns rsmd.getColumnCount() names of these columns rsmd.getColumnName(i) kind of data in each column rsmd.getColumnTypeName(i) ResultSet rs = st.executeQuery("SELECT.... ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); for (int i=1; i<= rsmd.getColumnCount(); i++) { System.out.print(rsmd.getColumnLabel(col) See Also: DatabaseMetaData
UFCE4Y Escape Sequences … make special characters literal. Wildcards st.executeQuery( "SELECT * from NAMES where id like 'SM\_%' {escape '\'}“ ); The "_" character is normally a wildcard for single character. Special Characters For example escaping the single quote inside a string.
UFCE4Y Where to go from here … Oracle JDBC tutorial Oracle JDBC tutorialJDBC tutorialJDBC tutorial See Links on the module home page Links Next CAS practical will use material from here … Next CAS practical will use material from here …