Download presentation
Presentation is loading. Please wait.
Published byEllen Harmon Modified over 9 years ago
1
UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson
2
UFCE4Y-20-32 JDBC Java Database Connectivity
3
UFCE4Y-20-33 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
4
UFCE4Y-20-34 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. http://en.wikipedia.org/wiki/Middleware
5
UFCE4Y-20-35 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
6
UFCE4Y-20-36 Client Server Model RDBMS SQL Oracle Files Code Cobol Code RDBMS SQL VB & Oracle GUI HTML RDBMS SQL Browser, Java & Oracle Code GUI
7
UFCE4Y-20-37 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
8
UFCE4Y-20-38 JDBC Structure Java Application JDBC Manager JDBC Bridge Database Vendor Tech.Java & NativeJava - ProtocolJava – Net http://java.sun.com/products/jdbc/driverdesc.html
9
UFCE4Y-20-39 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.
10
UFCE4Y-20-310 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.
11
UFCE4Y-20-311 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
12
UFCE4Y-20-312 Building a DB Saved as student.mdb
13
UFCE4Y-20-313 Add ODBC
14
UFCE4Y-20-314 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
15
UFCE4Y-20-315 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
16
UFCE4Y-20-316 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
17
UFCE4Y-20-317 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!
18
UFCE4Y-20-318 JDBC URLs The JDBC Driver use a JDBC URL to identify and connect to particular database. Eg: jdbc.odbc.studb jdbc.oracle.thin:@ivor:1526:csm1 jdbc.hsql:c/temp/appleDB jdbc.hsql.http://www..... Each driver is able to recognises it's own URLs
19
UFCE4Y-20-319 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.
20
UFCE4Y-20-320 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)
21
UFCE4Y-20-321 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.
22
UFCE4Y-20-322 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)
23
UFCE4Y-20-323 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.
24
UFCE4Y-20-324 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); }
25
UFCE4Y-20-325 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
26
UFCE4Y-20-326 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.
27
UFCE4Y-20-327 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 …
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.