Slides 02


Published on

  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • 4
  • Slides 02

    1. 1. CS122B: Projects in Database Management Winter 2010 Notes 2: Database Connectivity Professor Chen Li Department of Computer Science UC Irvine
    2. 2. Outline <ul><li>Motivation </li></ul><ul><li>Architecture </li></ul><ul><li>7 steps </li></ul><ul><li>Sample program </li></ul><ul><li>Metadata </li></ul>CS122B Notes 02: Database Connectivity
    3. 3. Motivation <ul><li>Most popular form of database system is the relational database system. </li></ul><ul><ul><li>Examples: MS Access, Sybase, Oracle, MS Sequel Server, Postgres. </li></ul></ul><ul><li>Structured Query Language (SQL) is used among relational databases to construct queries. </li></ul><ul><li>Applications need to query databases </li></ul>CS122B Notes 02: Database Connectivity
    4. 4. Simple Database Application CS122B Notes 02: Database Connectivity Ex: Access Oracle Sybase A P P L I C A T I O N DBMS DB
    5. 5. Multi-Databases CS122B Notes 02: Database Connectivity A P P L I C A T I O N DBMS 1 DBMS 2 DBMS 3 DB DB DB
    6. 6. Standard Access to DB CS122B Notes 02: Database Connectivity A P P L I C A T I O N D R I V E R M G R DBMS Driver 1 DBMS Driver 2 DBMS Driver 3 DBMS 1 DBMS 2 DBMS 3 DB DB DB
    7. 7. ODBC Architecture CS122B Notes 02: Database Connectivity Application Class1 Class2 Driver Manager DataSource2 DataSource1 DataSource3 ODBC DriverType1 DriverType2 DriverType3
    8. 8. Open Database Connectivity (ODBC) Standard <ul><li>ODBC standard is an interface by which application programs can access and process SQL databases in a DBMS-independent manner. It contains: </li></ul><ul><ul><li>A Data Source that is the database, its associated DBMS, operating system and network platform </li></ul></ul><ul><ul><li>A DBMS Driver that is supplied by the DBMS vendor (e.g., Oracle, IBM, MS) or independent software companies </li></ul></ul><ul><ul><li>A Driver Manager that is supplied by the vendor of the O/S platform (e.g., Windows/UNIX/Mac) where the application is running </li></ul></ul><ul><ul><li>E.g Control Panel->Administrative Tools->Data Sources (ODBC) </li></ul></ul><ul><ul><li>in Windows. You can use ODBC to access MS Access or even Excel documents using the corresponding drivers. </li></ul></ul>CS122B Notes 02: Database Connectivity
    9. 9. ODBC Interface <ul><li>System-independent interface to database environment </li></ul><ul><ul><li>requires an ODBC driver to be provided for each database system from which you want to manipulate data. </li></ul></ul><ul><li>The ODBC driver manager bridges the differences between </li></ul><ul><ul><li>The ODBC DBMS-independent interface and the DBMS-dependent interface of the DBMS driver </li></ul></ul>CS122B Notes 02: Database Connectivity
    10. 10. An Example CS122B Notes 02: Database Connectivity Application DriverManager MySQL Driver DB2 driver SQLServer driver odbc standard API
    11. 11. Java Support for Database Connectivity <ul><li>When applications written in Java want to access data sources, they use classes and associated methods provided by Java DBC (JDBC) API. </li></ul><ul><li>JDBC is specified an “interface.” </li></ul><ul><li>An interface in Java can have many “implementations.” </li></ul><ul><ul><li>it provides a convenient way to realize many “drivers” </li></ul></ul><ul><li>JDBC can be an interface to an ODBC driver manager. </li></ul><ul><li>Also it provides a JDBC API as a standard way to directly connect to common relational databases. </li></ul>CS122B Notes 02: Database Connectivity
    12. 12. Application in Java CS122B Notes 02: Database Connectivity Application in Java DriverManager odbc standard API jdbc API MySQL Driver DB2 driver SQLServer driver
    13. 13. Application in Java CS122B Notes 02: Database Connectivity Application in Java MySQL Driver Jdbc API
    14. 14. Java Support for SQL <ul><li>Java supports embedded SQL . </li></ul><ul><ul><li>Embedded SQL in Java (SQLJ is one version of it) p rovide s a standardized way for Java programs to interact with multi ple databases, but at a higher level than the existing JDBC API. </li></ul></ul><ul><ul><li>Embedded SQL allows connect ing to a database by includ ing SQL code right in the program . </li></ul></ul><ul><ul><li>An Embedded SQL preprocessor converts the SQL statements to Java code at pre-compile time.   The preprocessor generates code that includes the driver functionality for d irect connection to the  DBMS via JDBC. </li></ul></ul><ul><li>java.sql package and an extensive exception hierarchy. </li></ul><ul><li>We will examine a direct pure Java JDBC driver using sample code. </li></ul>CS122B Notes 02: Database Connectivity
    15. 15. An JDBC example <ul><li> </li></ul>CS122B Notes 02: Database Connectivity
    16. 16. Data Source and Driver <ul><li>Data source: database created using any of the common database applications. </li></ul><ul><li>Your system should have the driver for the database you will be using. </li></ul><ul><ul><li>E.g., MS SQL Server on a Windows system. </li></ul></ul><ul><li>There are a number of JDBC drivers available. </li></ul><ul><ul><li> </li></ul></ul>CS122B Notes 02: Database Connectivity
    17. 17. JDBC Components <ul><li>Driver Manager : Loads database drivers, and manages the connection between application & driver. </li></ul><ul><li>Driver : Translates API calls to operations for a specific data source. </li></ul><ul><li>Connection : A session between an application and a driver. </li></ul><ul><li>Statement : A SQL statement to perform a query or an update operation. </li></ul><ul><li>Metadata : Information about the returned data, driver and the database. </li></ul><ul><li>Result Set : Logical set of columns and rows returned by executing a statement. </li></ul>CS122B Notes 02: Database Connectivity
    18. 18. JDBC Classes <ul><li>Java supports DB facilities by providing classes and interfaces for its components </li></ul><ul><li>DriverManager class </li></ul><ul><li>Connection interface (abstract class) </li></ul><ul><li>Statement interface (to be instantiated with values from the actual SQL statement) </li></ul><ul><li>ResultSet interface </li></ul>CS122B Notes 02: Database Connectivity
    19. 19. java.sql <ul><li>JDBC is implemented via classes in the java.sql package </li></ul><ul><ul><li>Supports SQL-2 entry level </li></ul></ul><ul><li>Define objects for: </li></ul><ul><ul><li>Remote connection to DB </li></ul></ul><ul><ul><li>Executing query </li></ul></ul><ul><li>8 interfaces to define objects: </li></ul><ul><ul><li>Statement, CallableStatement, PreparedStatement, DatabaseMetaData, ResultSetMetaData, ResultSet, Connection, Driver </li></ul></ul>Notes 02: Database Connectivity
    20. 20. CS122B Notes 02: Database Connectivity DriverManager Driver Connection Statement ResultSet <ul><li>Load the driver </li></ul><ul><li>Define the Connection URL </li></ul><ul><li>Establish the Connection </li></ul><ul><li>Create a Statement object </li></ul><ul><li>Execute a query </li></ul><ul><li>Process the result </li></ul><ul><li>Close the connection </li></ul>Seven Steps
    21. 21. Loading the Driver <ul><li>Registering the driver directly automatically: </li></ul><ul><li>Class.forName(“ com.mysql.jdbc.Driver &quot;); </li></ul><ul><li>Calling Class.forName , which automatically </li></ul><ul><ul><li>creates an instance of the driver </li></ul></ul><ul><ul><li>registers the driver with the DriverManager </li></ul></ul>CS122B Notes 02: Database Connectivity
    22. 22. Identifying Data Sources <ul><li>Gives the required information for making the connection to the database </li></ul><ul><li>Specified using the URL format. </li></ul><ul><li><scheme>: <sub_scheme>:<scheme-specific-part> </li></ul><ul><li>Example: </li></ul><ul><li>jdbc:postgresql:// </li></ul><ul><li>jdbc:postgresql://localhost/testdb </li></ul><ul><li>jdbc:mysql:///mydb </li></ul>CS122B Notes 02: Database Connectivity
    23. 23. Connection <ul><li>A Connection represents a session with a specific database </li></ul><ul><li>Within the context of a Connection, SQL statements are executed and results are returned </li></ul>CS122B Notes 02: Database Connectivity
    24. 24. Connections <ul><li>There can be multiple connections to a database </li></ul><ul><li>A connection provides “metadata”, i.e., information about the database, tables, and fields </li></ul><ul><li>Connection object has methods to deal with transactions </li></ul>CS122B Notes 02: Database Connectivity
    25. 25. Creating a Connection <ul><li>Use getConnection on the Driver </li></ul><ul><li>Connection getConnection </li></ul><ul><li>(String url, </li></ul><ul><li> String user, </li></ul><ul><li> String password) </li></ul><ul><li>Connects to given JDBC URL with given user name and password </li></ul><ul><li>Throws java.sql.SQLException </li></ul><ul><li>returns a Connection object </li></ul>CS122B Notes 02: Database Connectivity
    26. 26. Creating a Connection <ul><li>Connection connection = DriverManager.getConnection(&quot;jdbc:mysql:///mydb&quot;, &quot;testuser&quot;, &quot;mypassword&quot;); </li></ul>CS122B Notes 02: Database Connectivity
    27. 27. Statements <ul><li>Statement createStatement() </li></ul><ul><ul><li>returns a new Statement object </li></ul></ul><ul><ul><li>Used for general queries </li></ul></ul><ul><li>PreparedStatement prepareStatement(String sql) </li></ul><ul><ul><li>returns a new PreparedStatement object </li></ul></ul><ul><ul><li>For a statement called multiple times with different values (precompiled to reduce parsing time) </li></ul></ul><ul><li>CallableStatement prepareCall(String sql) </li></ul><ul><ul><li>returns a new CallableStatement object </li></ul></ul><ul><ul><li>For stored procedures </li></ul></ul>CS122B Notes 02: Database Connectivity
    28. 28. Statements <ul><li>A Statement object is used for executing a static SQL statement and obtaining the results produced by it </li></ul><ul><li>executeQuery is used for statements that return an output result </li></ul><ul><li>executeUpdate is used for statements that need not return an output </li></ul>CS122B Notes 02: Database Connectivity
    29. 29. Executing Queries and Updates <ul><li>ResultSet executeQuery(String) </li></ul><ul><ul><li>Execute a SQL statement that returns a single ResultSet </li></ul></ul><ul><li>int executeUpdate(String) </li></ul><ul><ul><li>Execute a SQL INSERT, UPDATE or DELETE statement </li></ul></ul><ul><ul><li>Used for CREATE TABLE, DROP TABLE and ALTER TABLE </li></ul></ul><ul><ul><li>Returns the number of rows changed </li></ul></ul>CS122B Notes 02: Database Connectivity
    30. 30. Timeout <ul><li>Use setQueryTimeOut to set a timeout for the driver to wait for a statement to be completed </li></ul><ul><li>If the operation is not completed in the given time, an SQLException is thrown </li></ul><ul><li>What is it good for? </li></ul>CS122B Notes 02: Database Connectivity
    31. 31. Cursor <ul><li>What is the result of a query? </li></ul><ul><li>How can a database send the result of a query through communication lines? </li></ul><ul><li>The answer: using a cursor </li></ul>CS122B Notes 02: Database Connectivity
    32. 32. Result Set <ul><li>A ResultSet provides access to a table of data generated by executing a Statement </li></ul><ul><li>Only one ResultSet per Statement can be open at once </li></ul><ul><li>The table rows are retrieved in sequence </li></ul><ul><li>A ResultSet maintains a cursor pointing to its current row of data </li></ul><ul><li>The 'next' method moves the cursor to the next row </li></ul><ul><ul><li>you can’t rewind </li></ul></ul>CS122B Notes 02: Database Connectivity
    33. 33. Working with ResultSet <ul><li>boolean next() </li></ul><ul><ul><li>activates the next row </li></ul></ul><ul><ul><li>the first call to next() activates the first row </li></ul></ul><ul><ul><li>returns false if there are no more rows </li></ul></ul><ul><li>void close() </li></ul><ul><ul><li>disposes of the ResultSet </li></ul></ul><ul><ul><li>automatically called by most Statement methods </li></ul></ul>CS122B Notes 02: Database Connectivity
    34. 34. <ul><li>Type get Type (int columnIndex) </li></ul><ul><ul><li>returns the given field as the given type </li></ul></ul><ul><ul><li>E.g., int getInt(5); string getString(3); </li></ul></ul><ul><ul><li>fields indexed starting at 1 (not 0) </li></ul></ul><ul><li>Type get Type (String columnName) </li></ul><ul><ul><li>same, but uses name of field </li></ul></ul><ul><ul><li>less efficient </li></ul></ul><ul><li>int findColumn(String columnName) </li></ul><ul><ul><li>looks up column index given column name </li></ul></ul>Getting Values from Rows Notes 02: Database Connectivity
    35. 35. isNull <ul><li>In SQL, NULL means the field is empty </li></ul><ul><li>Not the same as 0 or “” </li></ul><ul><li>In JDBC, you must explicitly ask if a field is null by calling ResultSet.isNull(column) </li></ul>Notes 02: Database Connectivity
    36. 36. Mapping Java Types to SQL Types <ul><li>SQL type Java Type </li></ul><ul><li>CHAR, VARCHAR , LONGVARCHAR String </li></ul><ul><li>NUMERIC , DECIMAL java.math.BigDecimal </li></ul><ul><li>BIT boolean </li></ul><ul><li>TINYINT byte </li></ul><ul><li>SMALLINT short </li></ul><ul><li>INTEGER int </li></ul><ul><li>BIGINT long </li></ul><ul><li>REAL float </li></ul><ul><li>FLOAT, DOUBLE double </li></ul><ul><li>BINARY, VARBINARY , LONGVARBINARY byte[] </li></ul><ul><li>DATE java.sql.Date </li></ul><ul><li>TIME java.sql.Time </li></ul><ul><li>TIMESTAMP java.sql.Timestamp </li></ul>Notes 02: Database Connectivity
    37. 37. Database Time <ul><li>Times in SQL are nonstandard </li></ul><ul><li>Java defines three classes to help </li></ul><ul><li>java.sql.Date </li></ul><ul><ul><li>year, month, day </li></ul></ul><ul><li>java.sql.Time </li></ul><ul><ul><li>hours, minutes, seconds </li></ul></ul><ul><li>java.sql.Timestamp </li></ul><ul><ul><li>year, month, day, hours, minutes, seconds, nanoseconds </li></ul></ul><ul><ul><li>usually use this one </li></ul></ul>Notes 02: Database Connectivity
    38. 38. Optimized Statements <ul><li>Prepared Statements </li></ul><ul><ul><li>SQL calls that you make again and again </li></ul></ul><ul><ul><li>allows driver to optimize (compile) queries </li></ul></ul><ul><ul><li>created with Connection.prepareStatement() </li></ul></ul><ul><li>Stored Procedures </li></ul><ul><ul><li>written in DB-specific language </li></ul></ul><ul><ul><li>stored inside database </li></ul></ul><ul><ul><li>accessed with Connection.prepareCall() </li></ul></ul>CS122B Notes 02: Database Connectivity
    39. 39. Prepared Statement Example <ul><li>PreparedStatement updateSales; </li></ul><ul><li>String updateString = &quot; update COFFEES &quot; + </li></ul><ul><li>&quot; set SALES = ? where COF_NAME like ? &quot;; </li></ul><ul><li>updateSales = con.prepareStatement(updateString); </li></ul><ul><li>int [] salesForWeek = {175, 150, 60, 155, 90}; </li></ul><ul><li>String [] coffees = {&quot;Colombian&quot;, &quot;French_Roast&quot;, &quot;Espresso&quot;,&quot;Colombian_Decaf&quot;,&quot;French_Roast_Decaf&quot;}; </li></ul><ul><li>int len = coffees.length; </li></ul><ul><li>for(int i = 0; i < len; i++) { </li></ul><ul><li>updateSales.setInt(1, salesForWeek[i]); updateSales.setString(2, coffees[i]); updateSales.executeUpdate(); </li></ul><ul><li>} </li></ul>CS122B Notes 02: Database Connectivity
    40. 40. JDBC Class Diagram Notes 02: Database Connectivity
    41. 41. Metadata <ul><li>Connection: </li></ul><ul><ul><li>DatabaseMetaData getMetaData() </li></ul></ul><ul><li>ResultSet: </li></ul><ul><ul><li>ResultSetMetaData getMetaData() </li></ul></ul>CS122B Notes 02: Database Connectivity
    42. 42. ResultSetMetaData <ul><li>What's the number of columns in the ResultSet? </li></ul><ul><li>What's a column's name? </li></ul><ul><li>What's a column's SQL type? </li></ul><ul><li>What's the column's normal max width in chars? </li></ul><ul><li>What's the suggested column title for use in printouts and displays? </li></ul><ul><li>What's a column's number of decimal digits? </li></ul><ul><li>Does a column's case matter? </li></ul><ul><li>and so on... </li></ul>Notes 02: Database Connectivity
    43. 43. DatabaseMetaData <ul><li>What tables are available? </li></ul><ul><li>What's our user name as known to the database? </li></ul><ul><li>Is the database in read-only mode? </li></ul><ul><li>If table correlation names are supported (association of a column with the table it comes from, when multiple columns of the same name appear in the same query - multi-table queries) , are they restricted to be different from the names of the tables? </li></ul><ul><li>and so on… </li></ul>Notes 02: Database Connectivity
    44. 44. Useful Methods of Metadata <ul><li>getColumnCount </li></ul><ul><li>getColumnDisplaySize </li></ul><ul><li>getColumnName </li></ul><ul><li>getColumnType </li></ul><ul><li>isNullabale </li></ul><ul><li>Imagine the case where you want to print the result </li></ul>CS122B Notes 02: Database Connectivity
    45. 45. Transaction Management <ul><li>A transaction: a sequence of SQL statements </li></ul><ul><li>Transactions are not explicitly opened and closed </li></ul><ul><li>Instead, the connection has a state called AutoCommit mode </li></ul><ul><li>if AutoCommit is true, then every statement is automatically committed </li></ul><ul><li>default case: true </li></ul>CS122B Notes 02: Database Connectivity
    46. 46. AutoCommit <ul><li>Connection.setAutoCommit(boolean) </li></ul><ul><li>if AutoCommit is false, then every statement is added to an ongoing transaction </li></ul><ul><li>you must explicitly commit or rollback the transaction using Connection.commit() and Connection.rollback() </li></ul>CS122B Notes 02: Database Connectivity
    47. 47. AutoCommit (cont) <ul><li>Check: </li></ul><ul><li> </li></ul><ul><li> </li></ul><ul><li>There's a slight difference between doing them in SQL and JDBC: auto-commit control and commit call in JDBC are Java calls (not SQL). </li></ul>CS122B Notes 02: Database Connectivity
    48. 48. Connection Manager <ul><li>For a large threaded database server, create a Connection Manager object </li></ul><ul><li>It is responsible for maintaining a certain number of open connections to the database </li></ul><ul><li>When your applications need a connection, they ask for one from the CM’s pool </li></ul><ul><li>Why? Because opening and closing connections takes a long time </li></ul><ul><li>Warning: the CM should always setAutoCommit(false) when a connection is returned </li></ul>CS122B Notes 02: Database Connectivity
    49. 49. More info <ul><li>Go through the tutorial at: </li></ul><ul><li> </li></ul>CS122B Notes 02: Database Connectivity