1 / 31

Integrating Web Applications With Databases

Integrating Web Applications With Databases. A database is a collection of logically related data. It is usually managed bya a database management system (DBMS). For an RDBMS, the language standard that supports database operations is called Structured Query Language (SQL). Database Overview.

rufus
Télécharger la présentation

Integrating Web Applications With Databases

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Integrating Web Applications With Databases

  2. A database is a collection of logically related data. It is usually managed bya a database management system (DBMS). For an RDBMS, the language standard that supports database operations is called Structured Query Language (SQL). Database Overview

  3. An RDBMS allows you to perform four fundamental operations: Create a row in a table. Retrieve one or more rows in a table. Update some data in a table Delete one or more rows in a table. Database Overview

  4. JDBC is the Java technology API for interacting with a DBMS. The JDBC API includes interfaces that manage connections to the DBMS, statements to perform operations and result sets that encapsulate the result of retrieval operations. The JDBC API

  5. JDBC is a simple API for connecting from Java applications to multiple databases. Lets you smoothly translate between the world of the database, and the world of the Java application. The idea of a universal database access API is not a new one. For example, Open Database Connectivity (ODBC) was developed to create a single standard for database access in the Windows environment. JDBC API aims to be as simple as possible while providing developers with maximum flexibility. Introduction to JDBC

  6. To connect to a database, you first need a JDBC Driver. JDBC Driver: set of classes that interface with a specific database engine. Understanding JDBC Drivers Java Application JDBC Driver Manager JDBC- ODBC Bridge Vendor Specific JDBC Driver Vendor Specific JDBC Driver Database Database Diagram Source: Marty Hall, Core Web Programming (Prentice Hall.)

  7. JDBC drivers exist for every major database including: Oracle, SQL Server, Sybase, and MySQL. For MySQL, we will be using the open source MySQL Connector/J. http://www.mysql.com/downloads/api-jdbc.html. JDBC Drivers

  8. To use the MySQL Connector/J Driver, you need to download the complete distribution. Once you have extracted the distribution archive, you can install the driver by placing mysql-connector-java-[version]-bin.jar in your classpath, either by adding the FULL path to it to your CLASSPATH enviornment variable. To use the driver within Tomcat, copy the jar file above to: [TOMCAT_HOME]\webapps\ROOT\WEB-INF\lib Installing the MySQL Driver

  9. Load the JDBC Driver Establish the Database Connection Create a Statement Object Execute a Query Process the Results Close the Connection Six Steps to Using JDBC

  10. To use a JDBC driver, you must load the driver via the Class.forName() method. In general, the code looks like this: Class.forName("jdbc.DriverXYZ"); where jbdc.DriverXYZ is the JDBC Driver you want to load. If you are using a JDBC-ODBC Driver, your code will look like this: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 1) Loading the JDBC Driver

  11. With MySQL Connector/J, the name of this class is com.mysql.jdbc.Driver. With this method, you could use an external configuration file to supply the driver class name and driver parameters to use when connecting to a database. try{ Class.forName("com.mysql.jdbc.Driver"); } catch(java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage());} Class.forName() will throw a ClassNotFoundException if your CLASSPATH is not set up properly. Hence, it's a good idea to surround the forName() with a try/catch block. Loading the MySQL Driver

  12. Once you have loaded your JDBC driver, the next step is to establish a database connection. The following line of code illustrates the basic idea: Connection con = DriverManager.getConnection(url, "myLogin", "myPassword"); 2) Establish the Connection

  13. The only difficulty in establishing a connection is specifying the correct URL. In general, the URL has the following format: jdbc:subprotocol:subname. JDBC indicates that this is a JDBC Connection (no mystery there! ) The subprotocol identifies the driver you want to use. The subname identifies the database name/location. Creating a Connection URL

  14. If you are using the JDBC-ODBC Bridge driver, the JDBC URL will start with jdbc:odbc: . The rest of the URL is generally your data source name or database system. String url = "jdbc:odbc:basketball"; Connection con = DriverManager.getConnection(url, “admin", “adminpasswd"); Example - ODBC

  15. Here's how you might connect to MySQL: String url = "jdbc:mysql://localhost/basketball"; Connection con = DriverManager.getConnection(url); In this case, we are using the MySQL JDBC Driver to connect to the basketball database, located on the localhost machine. If this code executes successfully, we will have a Connection object for communicating directly with the database. Example - MySQL

  16. The JDBC Statement object sends SQL statements to the database. Statement objects are created from active Connection objects. For example: Statement stmt = con.createStatement(); With a Statement object, you can issue SQL calls directly to the database. 3) Create a Statement Object

  17. executeQuery() Executes the SQL query and returns the data in a table (ResultSet) The resulting table may be empty but never null ResultSet results =stmt.executeQuery("SELECT a, b FROM table"); executeUpdate() Used to execute for INSERT, UPDATE, or DELETE SQL statements The return is the number of rows that were affected in the database Supports Data Definition Language (DDL) statements CREATE TABLE, DROP TABLE and ALTER TABLE 4) Execute a Query

  18. getMaxRows/setMaxRows Determines the number of rows a ResultSet may contain Unless explicitly set, the number of rows are unlimited (return value of 0) getQueryTimeout/setQueryTimeout Specifies the amount of a time a driver will wait for a STATEMENT to complete before throwing a SQLException Useful Statement Methods

  19. A ResultSet contains the results of the SQL query. Useful Methods All methods can throw a SQLException close Releases the JDBC and database resources The result set is automatically closed when the associated Statement object executes a new query getMetaDataObject Returns a ResultSetMetaData object containing information about the columns in the ResultSet 5) Process the Results

  20. Useful Methods next Attempts to move to the next row in the ResultSet If successful true is returned; otherwise, false The first call to next positions the cursor a the first row ResultSet (Continued)

  21. Useful Methods findColumn Returns the corresponding integer value corresponding to the specified column name Column numbers in the result set do not necessarily map to the same column numbers in the database getXxx Returns the value from the column specified by column name or column index as an Xxx Java type Returns 0 or null, if the value is a SQL NULL Legal getXxx types: ResultSet (Continued) double byte int Date String float short long Time Object

  22. To close the database connection: stmt.close(); connection.close(); Note: Some application servers, such as BEA WebLogic maintain a pool of database connections. This is much more efficient, as applications do not have the overhead of constantly opening and closing database connections. 6) Close the Connection

  23. To build a database application you must design the relationship between the Model objects and the corresponding database representation. To design the Model elements of an application, you should perform the following tasks: Design the domain objects of your application Design the database tables that map to the domain objects Design the business services (the Model) to separate the database code into classes using the DAO pattern. Designing a Web ApplicationUsing Database

  24. Domain objects represent the real-world business entities of your application. Case Study: The BasketballLeague * * League Player objectID year season title objectID name address city province postal_code Registration division

  25. Each domain objects has a corresponding DB table. Database Tables <<DB Table>> League <<DB Table>> Player * * << DB Table>> Registration LID year season title objectID name address city province postal_code LID PID division << DB Table>> ObjectIDs table_name ID_number

  26. Example Data

  27. The DAO pattern makes it easier to maintain applications that use databases by separating the business logic from the data access logic. The DAO pattern permits the business logic and the data access logic to change independently. Data Access Object (DAO) Pattern

  28. DAO Pattern Example Player RegisterService +getLeague +getPlayer +register <<package-private>> PlayerDAO Registration servlet insert <<package-private>> ObjectIDDAO League RegisterService getNextObjectID +getLeague +createLeague <<package-private>> LeagueDAO LeagueAdmin servlet retrieve insert

  29. Business logic and data access logic are now separate. The data access objects promote reuse and flexibility in changing the system. Developers writing other servlets can reuse the same data access code. This design makes it easy to change front-end technologies. This design makes it easy to change back-end technologies. Advantages of the DAO Pattern

  30. The DAO pattern hides the details of the data access logic from the rest of the system. The DAO classes require connections to access data in a DBMS. To develop a Web application that uses a connection pool (CP) with the DAO pattern, consider the ff: Build or buy a CP subsystem Store the CP object in a global “name space” Design your DAOs to use the CP, retrieving it from the name space Develop a servlet context listener to initialize the CP and store it in the name space Using a Connection Pool

  31. Connection Pool

More Related