Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Server-Side Web Development using JSP and Databases

Similar presentations


Presentation on theme: "Introduction to Server-Side Web Development using JSP and Databases"— Presentation transcript:

1 Introduction to Server-Side Web Development using JSP and Databases
03th March 2005 Bogdan L. Vrusias

2 Contents Relational Databases Transactions Middleware
Basic Java classes used for databases Integrating JSP and Data 03th March 2005 Bogdan L. Vrusias © 2005

3 Relational Databases and SQL
A relational database consists of a series of tables and is normally accessed using a special programming language known as SQL (Structured Query Language) often embedded within another language such as Java or C++. With the exception of a few object-oriented database products released in the late 1980s and the 1990s relational database technology has been the overwhelmingly dominant database technology for the last 20 years. 03th March 2005 Bogdan L. Vrusias © 2005

4 Database Middleware There is a wide variety of middleware available which fits between clients and database servers: The first most popular component is an SQL API (Application Programmer’s Interface). This provides programming facilities for developers who wish, for example, to embed SQL code within procedural languages. The second most popular is a database driver. This is usually a small piece of software which takes SQL statements, formats them and then sends them over to the server. 03th March 2005 Bogdan L. Vrusias © 2005

5 JDBC Driver JDBC driver is a piece of software that knows how to talk to a database server. Java Application JDBC API JDBC Driver Manager JDBC Driver API JDBC-ODBC Bridge Ventor Specific JDBC Driver Ventor Specific ODBC Driver Database Database 03th March 2005 Bogdan L. Vrusias © 2005

6 The Basic Java Classes The vast majority of the classes used for accessing SQL databases can be found in the java.sql package. The functions of these classes are: Driver. This is a class associated with the database driver that is used to communicate with a database. This class is not usually accessed by the programmer. Connection. This is the class which contains facilities for connecting to a database. Execution of SQL statements is associated with a database connected to a Connection object. Statement. This class is used to create and execute SQL statements. PreparedStatement. This class is used to develop SQL statements which have an increased efficiency when executed a number of times with different arguments. CallableStatement. This class provides the programmer with the facilities for calling stored procedures. 03th March 2005 Bogdan L. Vrusias © 2005

7 The Basic Java Classes II
ResultSet. When an SQL statement is executed a result set is usually returned. This result set will contain objects which are rows of the table which has been created by the query. ResultSetMetaData. There are a collection of classes in java.sql which provide data about the main entities that this package manipulates. This class provides metadata information about result sets extracted as a result of queries. DatabaseMetaData. This is another metadata class. In this case it provides information about a database. For example, it enables the programmer to discover whether the database supports stored procedures, whether the database supports ANSI92 SQL and what the product version of the database is. DriverManager. This is a class that manages the drivers that are available for connecting to a database. DriverPropertyInfo. This class is not used by application programmers. It contains a number of instance variables which are used by drivers in order to connect into a relational database. 03th March 2005 Bogdan L. Vrusias © 2005

8 Accessing a Database: Processing Steps
Load a driver which is compatible with the database that is to be processed. Define and establish a connection to the database. Associate an SQL statement with this connection. Execute the SQL statement. The SQL statement which has been executed will produce a table which is stored in a ResultSet object. This object will contain a reference to the rows of the table that has been formed by the execution of the SQL statement. Execute further SQL statements as above. When the processing associated with the database is complete the database is closed and the connection to the database is also closed. 03th March 2005 Bogdan L. Vrusias © 2005

9 Accessing a Database: Example I
try { // Load in the driver programmatically Class.forName("org.gjt.mm.mysql.Driver"); } catch (ClassNotFoundException cnf) //Problem with driver, display error message System.out.println("Problem loading driver: " + cnf); (Continues next page…) 03th March 2005 Bogdan L. Vrusias © 2005

10 Accessing a Database: Example II
try { Connection con = DriverManager.getConnection( "jdbc:mysql://mysql0.ee.surrey.ac.uk:3306/webtech", "webtech", "webtech"); Statement st = con.createStatement(); ResultSet rs=st.executeQuery("SELECT * FROM images;"); ... while(rs.next()){ anInteger = rs.getInteger(1); aString = rs.getString(2); ... } st.close(); con.close(); rs.close(); catch(Exception e){ ... } 03th March 2005 Bogdan L. Vrusias © 2005

11 Define and Establish the Connection
Create a connection object Connection conn = null; Load the JDBC driver and connect to the database Class.forName("driver..."); conn = DriverManager.getConnection("url..." , [Username], [Password]); NOTE: All functions of connecting and using a database should be enclosed within a try-catch block. NOTE: A database connection should always be closed after the code has finished using the database. 03th March 2005 Bogdan L. Vrusias © 2005

12 Create a Statement Object and Execute
Create a Statement object and execute the SQL Statement st = conn.createStatement(); // for selecting records ResultSet rs = st.executeQuery("query..."); or // for inserting, deleting or updating records int numRows = st.executeUpdate("query..."); NOTE: Capturing exceptions is important and should not be ignored 03th March 2005 Bogdan L. Vrusias © 2005

13 Process the Results Grab the ResultSet and ResultSetMetaData ResultSet
ResultSet rs = statement.getResultSet(); ResultSetMetaData rm = rs.getMetaData(); ResultSet rs.next(); rs.getXxx(); rs.getString(1); // column id rs.getString("name"); // column name rs.getInteger(2); ResultSetMetaData rm.getColumnCount(); rm.getColumnName(1); rm.getColumnType(1); 03th March 2005 Bogdan L. Vrusias © 2005

14 Example: Displaying results on a Table
First (based on previous 3 slides): Define and Establish the Connection Create a Statement Object and Execute the SQL Process the Results Then, get number of columns and build a list of column names int columns = rm.getColumnCount(); result = "<tr>"; for ( int i = 1; i <= columns; i++){ result += "<td>" + rm.getColumnLabel(i) + "</td>"; } result += "</tr>"; 03th March 2005 Bogdan L. Vrusias © 2005

15 Example: Displaying results on a Table
Then, get the actual data while(rs.next()) { rs.getRow(); result += "<tr>"; for ( int i = 1; i <= columns; i++) { result += "<td>" + rs.getObject(i).toString() + "</td>"; } result += "</tr>"; Finally, print the results on the JSP page <table border="1"> <%=result%> </table> 03th March 2005 Bogdan L. Vrusias © 2005

16 Example: Advanced Catch
... catch (ClassNotFoundException e) { result = " <tr><td>Database drive Error!"; result += " <br/>" + e.toString() + "</td></tr>"; } catch (SQLException e) { result = " <tr><td> Error processing the SQL!"; result += " <br/>" + e.toString()+ "</td></tr>"; finally { /* We must close the database connection now */ try { if (conn != null) { conn.close(); } { result = "<tr><td> Closing connection Error"; result += "<br/>"+ e.toString() +"</td></tr>"; } ... 03th March 2005 Bogdan L. Vrusias © 2005

17 Example: Dynamic SQL Generation
search.jsp ... <form name="form1" action="showResults.jsp"> <input type="text" name="imageID"/> </form> showResults.jsp String imgID = request.getParameter("imageID"); String sql = "select * from images where id=" + imgID; 03th March 2005 Bogdan L. Vrusias © 2005

18 Database Transactions
A database which will be the target of a number of transactions that will update it can be in two states. The first is the autocommit state. In this state any change that is required to the database occurs automatically. The second state is often referred to as the manual commit state. Here changes occur when the programmer explicitly issues a commit command. What this does is to apply all those changes to a database which have been saved up from the last commit command or a command known as a rollback command. 03th March 2005 Bogdan L. Vrusias © 2005

19 Issues I Connection Pooling Testing Components
Connections to a database are the most expensive operations performed in terms of time and resources. A method to control the database connections is called “connection pooling”. This should be used to speed up database access and reduce the number of database connections used by any Web application. Testing Components Driver software (or components) doesn’t always work as expected. Nothing is bug free. Budgeting time and resources to deal with unexpected problems should always be considered when working with components. 03th March 2005 Bogdan L. Vrusias © 2005

20 Issues II Testing for Scale Basic Design Concepts
Always test with realistic data sizes. Large final datasets will always clutter your system if you haven’t prepared for it. Basic Design Concepts JSP should be used at the presentation layer. All reusable or modular logic should be pushed into a JavaBean or Tag library (Business Objects). Reusable code. Modular and easier to update and maintain. Never put presentation level functionality into lower-level components such as JavaBeans. 03th March 2005 Bogdan L. Vrusias © 2005

21 Closing Questions??? Remarks??? Comments!!! Evaluation!
03th March 2005 Bogdan L. Vrusias © 2005


Download ppt "Introduction to Server-Side Web Development using JSP and Databases"

Similar presentations


Ads by Google