Presentation is loading. Please wait.

Presentation is loading. Please wait.

2006.11.02 SLIDE 1IS 257 – Fall 2006 JDBC and Java Access to DBMS University of California, Berkeley School of Information IS 257: Database Management.

Similar presentations


Presentation on theme: "2006.11.02 SLIDE 1IS 257 – Fall 2006 JDBC and Java Access to DBMS University of California, Berkeley School of Information IS 257: Database Management."— Presentation transcript:

1 2006.11.02 SLIDE 1IS 257 – Fall 2006 JDBC and Java Access to DBMS University of California, Berkeley School of Information IS 257: Database Management

2 2006.11.02 SLIDE 2IS 257 – Fall 2006 Lecture Outline Review: –Object-Relational DBMS –OR features in Oracle –OR features in PostgreSQL –Extending OR databases (examples from PostgreSQL) Java and JDBC

3 2006.11.02 SLIDE 3IS 257 – Fall 2006 Lecture Outline Object-Relational DBMS –OR features in Oracle –OR features in PostgreSQL Extending OR databases (examples from PostgreSQL) Java and JDBC

4 2006.11.02 SLIDE 4IS 257 – Fall 2006 Object Relational Data Model Class, instance, attribute, method, and integrity constraints OID per instance Encapsulation Multiple inheritance hierarchy of classes Class references via OID object references Set-Valued attributes Abstract Data Types

5 2006.11.02 SLIDE 5IS 257 – Fall 2006 Object Relational Extended SQL (Illustra) CREATE TABLE tablename {OF TYPE Typename}|{OF NEW TYPE typename} (attr1 type1, attr2 type2,…,attrn typen) {UNDER parent_table_name}; CREATE TYPE typename (attribute_name type_desc, attribute2 type2, …, attrn typen); CREATE FUNCTION functionname (type_name, type_name) RETURNS type_name AS sql_statement

6 2006.11.02 SLIDE 6IS 257 – Fall 2006 Object-Relational SQL in ORACLE CREATE (OR REPLACE) TYPE typename AS OBJECT (attr_name, attr_type, …); CREATE TABLE OF typename;

7 2006.11.02 SLIDE 7IS 257 – Fall 2006 Example CREATE TYPE ANIMAL_TY AS OBJECT (Breed VARCHAR2(25), Name VARCHAR2(25), Birthdate DATE); Creates a new type CREATE TABLE Animal of Animal_ty; Creates “Object Table”

8 2006.11.02 SLIDE 8IS 257 – Fall 2006 Constructor Functions INSERT INTO Animal values (ANIMAL_TY(‘Mule’, ‘Frances’, TO_DATE(‘01-APR-1997’, ‘DD-MM- YYYY’))); Insert a new ANIMAL_TY object into the table

9 2006.11.02 SLIDE 9IS 257 – Fall 2006 PostgreSQL Classes The fundamental notion in Postgres is that of a class, which is a named collection of object instances. Each instance has the same collection of named attributes, and each attribute is of a specific type. Furthermore, each instance has a permanent object identifier (OID) that is unique throughout the installation. Because SQL syntax refers to tables, we will use the terms table and class interchangeably. Likewise, an SQL row is an instance and SQL columns are attributes.

10 2006.11.02 SLIDE 10IS 257 – Fall 2006 Creating a Class You can create a new class by specifying the class name, along with all attribute names and their types: CREATE TABLE weather ( city varchar(80), temp_lo int, -- low temperature temp_hi int, -- high temperature prcp real, -- precipitation date date );

11 2006.11.02 SLIDE 11IS 257 – Fall 2006 PostgreSQL Postgres can be customized with an arbitrary number of user-defined data types. Consequently, type names are not syntactical keywords, except where required to support special cases in the SQL92 standard. So far, the Postgres CREATE command looks exactly like the command used to create a table in a traditional relational system. However, we will presently see that classes have properties that are extensions of the relational model.

12 2006.11.02 SLIDE 12IS 257 – Fall 2006 Inheritance CREATE TABLE cities ( name text, population float, altitude int -- (in ft) ); CREATE TABLE capitals ( state char(2) ) INHERITS (cities);

13 2006.11.02 SLIDE 13IS 257 – Fall 2006 Inheritance In Postgres, a class can inherit from zero or more other classes. A query can reference either –all instances of a class –or all instances of a class plus all of its descendants

14 2006.11.02 SLIDE 14IS 257 – Fall 2006 Non-Atomic Values - Arrays The preceding SQL command will create a class named SAL_EMP with a text string (name), a one-dimensional array of int4 (pay_by_quarter), which represents the employee's salary by quarter and a two-dimensional array of text (schedule), which represents the employee's weekly schedule Now we do some INSERTSs; note that when appending to an array, we enclose the values within braces and separate them by commas.

15 2006.11.02 SLIDE 15IS 257 – Fall 2006 PostgreSQL Extensibility Postgres is extensible because its operation is catalog- driven –RDBMS store information about databases, tables, columns, etc., in what are commonly known as system catalogs. (Some systems call this the data dictionary). One key difference between Postgres and standard RDBMS is that Postgres stores much more information in its catalogs –not only information about tables and columns, but also information about its types, functions, access methods, etc. These classes can be modified by the user, and since Postgres bases its internal operation on these classes, this means that Postgres can be extended by users –By comparison, conventional database systems can only be extended by changing hardcoded procedures within the DBMS or by loading modules specially-written by the DBMS vendor.

16 2006.11.02 SLIDE 16IS 257 – Fall 2006 Lecture Outline Review –Object-Relational DBMS –OR features in Oracle –OR features in PostgreSQL –Extending OR databases (examples from PostgreSQL) Java and JDBC

17 2006.11.02 SLIDE 17IS 257 – Fall 2006 Java and JDBC Java is probably the high-level language used in most software development today one of the earliest “enterprise” additions to Java was JDBC JDBC is an API that provides a mid-level access to DBMS from Java applications Intended to be an open cross-platform standard for database access in Java Similar in intent to Microsoft’s ODBC

18 2006.11.02 SLIDE 18IS 257 – Fall 2006 JDBC Architecture The goal of JDBC is to be a generic SQL database access framework that works for any database system with no changes to the interface code OracleMySQLPostgres Java Applications JDBC API JDBC Driver Manager Driver

19 2006.11.02 SLIDE 19IS 257 – Fall 2006 JDBC Provides a standard set of interfaces for any DBMS with a JDBC driver – using SQL to specify the databases operations. Resultset Statement Resultset Connection PreparedStatementCallableStatement DriverManager Oracle Driver ODBC DriverPostgres Driver Oracle DBPostgres DBODBC DB Application

20 2006.11.02 SLIDE 20IS 257 – Fall 2006 JDBC Simple Java Implementation import java.sql.*; import oracle.jdbc.*; public class JDBCSample { public static void main(java.lang.String[] args) { try { // this is where the driver is loaded //Class.forName("jdbc.oracle.thin"); DriverManager.registerDriver(new OracleDriver()); } catch (SQLException e) { System.out.println("Unable to load driver Class"); return; }

21 2006.11.02 SLIDE 21IS 257 – Fall 2006 JDBC Simple Java Impl. try { //All DB access is within the try/catch block... // make a connection to ORACLE on Dream Connection con = DriverManager.getConnection( "jdbc:oracle:thin:@dream.sims.berkeley.edu:1521:dev", “mylogin", “myoraclePW"); // Do an SQL statement... Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT NAME FROM DIVECUST");

22 2006.11.02 SLIDE 22IS 257 – Fall 2006 JDBC Simple Java Impl. // show the Results... while(rs.next()) { System.out.println(rs.getString("NAME")); } // Release the database resources... rs.close(); stmt.close(); con.close(); } catch (SQLException se) { // inform user of errors... System.out.println("SQL Exception: " + se.getMessage()); se.printStackTrace(System.out); }

23 2006.11.02 SLIDE 23IS 257 – Fall 2006 JDBC Once a connection has been made you can create three different types of statement objects Statement –The basic SQL statement as in the example PreparedStatement –A pre-compiled SQL statement CallableStatement –Permits access to stored procedures in the Database

24 2006.11.02 SLIDE 24IS 257 – Fall 2006 JDBC Resultset methods Next() to loop through rows in the resultset To access the attributes of each row you need to know its type, or you can use the generic “getObject()” which wraps the attribute as an object

25 2006.11.02 SLIDE 25IS 257 – Fall 2006 JDBC “GetXXX()” methods SQL data typeJava TypeGetXXX() CHARStringgetString() VARCHARStringgetString() LONGVARCHARStringgetString() NUMERICJava.math. BigDecimal GetBigDecimal() DECIMALJava.math. BigDecimal GetBigDecimal() BITBooleangetBoolean() TINYINTBytegetByte()

26 2006.11.02 SLIDE 26IS 257 – Fall 2006 JDBC GetXXX() Methods SQL data typeJava TypeGetXXX() SMALLINTInteger (short)getShort() INTEGERIntegergetInt() BIGINTLonggetLong() REALFloatgetFloat() FLOATDoublegetDouble() DOUBLEDoublegetDouble() BINARYByte[]getBytes() VARBINARYByte[]getBytes() LONGVARBINARYByte[]getBytes()

27 2006.11.02 SLIDE 27IS 257 – Fall 2006 JDBC GetXXX() Methods SQL data type Java TypeGetXXX() DATEjava.sql.DategetDate() TIMEjava.sql.TimegetTime() TIMESTAMPJava.sql.TimestampgetTimeStamp()

28 2006.11.02 SLIDE 28IS 257 – Fall 2006 Large Object Handling Large binary databytes can be read from a resultset as streams using: –getAsciiStream() –getBinaryStream() –getUnicodeStream() ResultSet rs = stmt.executeQuery(“SELECT IMAGE FROM PICTURES WHERE PID = 1223”)); if (rs.next()) { BufferedInputStream gifData = new BufferedInputSteam( rs.getBinaryStream(“IMAGE”)); byte[] buf = new byte[4*1024]; // 4K buffer int len; while ((len = gifData.read(buf,0,buf.length)) != -1) { out.write(buf, 0, len); }

29 2006.11.02 SLIDE 29IS 257 – Fall 2006 JDBC Metadata There are also methods to access the metadata associated with a resultSet –ResultSetMetaData rsmd = rs.getMetaData(); Metadata methods include… –getColumnCount(); –getColumnLabel(col); –getColumnTypeName(col)

30 2006.11.02 SLIDE 30IS 257 – Fall 2006 JDBC access to MySQL The basic JDBC interface is the same, the only differences are in how the drivers are loaded public class JDBCTestMysql { public static void main(java.lang.String[] args) { try { // this is where the driver is loaded Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (InstantiationException i) { System.out.println("Unable to load driver Class"); return; } catch (ClassNotFoundException e) { System.out.println("Unable to load driver Class"); …

31 2006.11.02 SLIDE 31IS 257 – Fall 2006 JDBC for MySQL try { //All DB access is within the try/catch block... // make a connection to MySQL on Dream Connection con = DriverManager.getConnection( "jdbc:mysql://dream.sims.berkeley.edu/ (this is really one line) MyDatabase?user=MyLogin&password=MySQLPW"); // Do an SQL statement... Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT NAME FROM DIVECUST"); Otherwise everything is the same as in the Oracle example For connecting to the machine you are running the program on, you can use “localhost” instead of the machine name


Download ppt "2006.11.02 SLIDE 1IS 257 – Fall 2006 JDBC and Java Access to DBMS University of California, Berkeley School of Information IS 257: Database Management."

Similar presentations


Ads by Google