DT211/3 Internet Application Development Databases.

Slides:



Advertisements
Similar presentations
DT211/3 Internet Application Development JSP: Processing User input.
Advertisements

DT211/3 Internet Application Development
1 C. Shahabi Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California
DT228/3 Web Development JSP: Directives and Scripting elements.
DT228/3 Web Development Databases. Database Almost all web application on the net access a database e.g. shopping sites, message boards, search engines.
Chapter 14: Advanced Topics: DBMS, SQL, and ASP.NET
Computer Science 101 Web Access to Databases Overview of Web Access to Databases.
ECE356 – Database Systems Lab 1 – Building a Web Project with NetBeans Tiuley Alguindigue Lab Instructor – University of Waterloo, E & CE Dept. Fall 2013.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Dataface API Essentials Steve Hannah Web Lite Solutions Corp.
M. Taimoor Khan * Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic,
JSP Standard Tag Library
Reading Data in Web Pages tMyn1 Reading Data in Web Pages A very common application of PHP is to have an HTML form gather information from a website's.
CSCI 6962: Server-side Design and Programming Course Introduction and Overview.
CHAPTER 9 DATABASE MANAGEMENT © Prepared By: Razif Razali.
A Guide to SQL, Eighth Edition Chapter Three Creating Tables.
Session 5: Working with MySQL iNET Academy Open Source Web Development.
JDBC Java Database Connectivity. What is an RDBMS? Relational database management system. There are other kinds of DBMS. Access is a GUI on a JET RBDMS.
INTERNET APPLICATION DEVELOPMENT For More visit:
CSCI 6962: Server-side Design and Programming JDBC Database Programming.
4-1 INTERNET DATABASE CONNECTOR Colorado Technical University IT420 Tim Peterson.
Advanced Database Management System Lab no. 11. SQL Commands (for MySQL) –Update –Replace –Delete.
Chapter 7 PHP Interacts with Ms. Access (Open DataBase Connectivity (ODBC))
Java Database Connectivity (JDBC) Introduction to JDBC JDBC is a simple API for connecting from Java applications to multiple databases. Lets you smoothly.
Database Programming in Java Corresponds with Chapter 32, 33.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
CIS 270—Application Development II Chapter 25—Accessing Databases with JDBC.
Active Server Pages ASP is Microsoft’s server-side script engine for dynamically-generated web pages. Most common language used is VBScript. If you use.
 Embeds Java code  In HTML tags  When used well  Simple way to generate dynamic web-pages  When misused (complex embedded Java)  Terribly messy.
M1G Introduction to Database Development 6. Building Applications.
Web Server Administration Chapter 7 Installing and Testing a Programming Environment.
1 Accelerated Web Development Course JavaScript and Client side programming Day 2 Rich Roth On The Net
1 Working with MS SQL Server Textbook Chapter 14.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Working with MSSQL Server Code:G0-C# Version: 1.0 Author: Pham Trung Hai CTD.
JAVA SERVER PAGES CREATING DYNAMIC WEB PAGES USING JAVA James Faeldon CS 119 Enterprise Systems Programming.
15/10/20151 PHP & MySQL 'Slide materials are based on W3Schools PHP tutorial, 'PHP website 'MySQL website.
Introduction to MySQL Lab no. 10 Advance Database Management System.
PHP MySQL Introduction. MySQL is the most popular open-source database system. What is MySQL? MySQL is a database. The data in MySQL is stored in database.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
NMED 3850 A Advanced Online Design January 12, 2010 V. Mahadevan.
SYST Web Technologies SYST Web Technologies Databases & MySQL.
JSTL Lec Umair©2006, All rights reserved JSTL (ni) Acronym of  JavaServer Pages Standard Tag Library JSTL (like JSP) is a specification, not an.
Chapter 6 Server-side Programming: Java Servlets
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
M1G Introduction to Database Development 2. Creating a Database.
Java Database Connectivity (JDBC). Topics 1. The Vendor Variation Problem 2. SQL and Versions of JDBC 3. Creating an ODBC Data Source 4. Simple Database.
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
DT228/3 Web Development Databases. Querying a database: Partial info Search engines, on-line catalogues often need to allow user to search a database.
Li Tak Sing COMPS311F. Database programming JDBC (Java Database Connectivity) Java version of ODBC (Open Database Connectivity) ODBC provides a standard.
Creating a simple database This shows you how to set up a database using PHPMyAdmin (installed with WAMP)
DataBases and SQL INFSY 547 Spring Course Wrap Up April 12: Complete Work on Servlets Review of Team Projects Close of Portfolio Work April 19:
JAVA BEANS JSP - Standard Tag Library (JSTL) JAVA Enterprise Edition.
Database Access Using JDBC BCIS 3680 Enterprise Programming.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
CSI 3125, Preliminaries, page 1 JDBC. CSI 3125, Preliminaries, page 2 JDBC JDBC stands for Java Database Connectivity, which is a standard Java API (application.
Basics of JDBC Session 14.
Chapter 6 Chapter 6 Server Side Programming (JSP) Part 1 1 (IS 203) WebProgramming (IS 203) Web Programming.
DT228/3 Web Development JSP: Actions elements and JSTL.
1 A Very Brief Introduction to Relational Databases.
In the Name Of Almighty Allah. Java Application Connection To Mysql Created by Hasibullah (Sahibzada) Kabul Computer Science Faculty Afghanistan.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
A Presentation Presentation On JSP On JSP & Online Shopping Cart Online Shopping Cart.
DEPTT. OF COMP. SC & APPLICATIONS
Chapter 5 Introduction to SQL.
JSP: Actions elements and JSTL
JDBC Database Management Database connectivity
ISC440: Web Programming 2 Server-side Scripting PHP 3
Introduction of Week 11 Return assignment 9-1 Collect assignment 10-1
Presentation transcript:

DT211/3 Internet Application Development Databases

Database Almost all web application on the net access a database e.g. shopping sites, message boards, search engines Relational databases (uses tables) are the most common type used Small application may use just one table, larger applications may have have hundreds of tables In JSP, database access can be done using scriplets or using JSTL JSTL supplies the SQL library to enable database access

Relational DBs Data is stored in tables. Rows and columns in tables can be related to rows and columns in other tables in the dB Each table usually has a primary key Structured Query Language (SQL) is used to query the database Common SQL Statements: SELECT, INSERT, UPDATE, DELETE customer IDNamePhone 1 John Liz Rory SELECT * from customers? SELECT name, phone from customers where customer_ID = 2 ? Row Column

Relational DBs INSERT INSERT INTO CUSTOMERS (customer_ID, name, phone) VALUES (5, “JOHN”, “875895”) UPDATE UPDATE CUSTOMERS SET NAME = “Robert” WHERE CUSTOMER_ID = 1 DELETE DELETE FROM CUSTOMERS WHERE CUSTOMER_ID = 2

Some Database concepts To access a database from a web application, need a path or connection to the database To support multiple connections to the same database - have connection pooling. Works like a group of connections that are used by clients as needed and “put back” in the pool as needed. Each database engine (e.g. Oracle, SQLServer, Access) needs its own database driver (The driver is just a piece of software that translate SQL calls between the web application to the database). Web applications have to “load” the appropriate driver in order to connect to the database

Some Database concepts Java provides the JDBC API (Java Database Connectivity API) to enable a uniform interface to different database engines JDBC enables java code that accesses a databases to be portable from one database to another (provided the correct driver is used). Many databases have an ODBC (Open Database Connectivity) interface (e.g. access) Sun provides a JDBC-ODBC driver for development purposes

JDBC-ODBC driver enables java (and JSP) applications to connect to ODBC databases, using the JDBC API Note: In production environment, should use a production quality driver from the database vendor Some Database concepts

Databases and web application Variety of databases available for use by web applications typically will use relational database with support for Structured Query Language Examples of common databases used: SQL server, MySQL, Oracle, Access

Datasource names (DSNs) To use a database in a web application need to say: - What the database is called - Where is resides - What driver is required by the database ODBC databases allow a Data source name to be used as a quick way to specify the above within the applicaton e.g., rather than saying “I want to connect to an Access2000 database named Exams.mdb in d:\samples\database directory in every JSP page that uses the particular database, will rather create a DSN named Exams Note: not all databases will support DSNs.

Datasource names (DSNs) To SET UP a data source name in Windows: Go to Windows control panel / administrative tools / system DSN (NOT user DSN) Add a new database source, selecting appropriate driver Note: Will use microsoft access for development purposes – it’s an ODBC database and supports DSNs

Accessing a database from JSP Need to identify and connect to the database to be used with the JSP page: 1) Global datasource: Can specifying a default datasource in a Tomcat configuration file for the application called the web.xml file. The datasource will automatically be made available to the JSP if done this way – Good approach for larger applications. OR 2) Direct from JSP: by specifying the database details directly within the JSP page. Use instead of (1) all the time OR just to override the default data source specified in (1)

Will cover 1) on next course. Good for larger applications. Will use 2) for development purposes. (Useful for smaller applications - but does not support connection pooling) Using option 2): Can use java code (via scriptlets) OR JSTL tags to access databases. We’ll use JSTL here. Full description of tags in JSTL documentation Note: To use JSTL tags, need to include the appropriate directive into the JSP page Accessing a database directly from JSP page

Use the action from the JSTL SQL library and specify the attributes it needs The action creates a database connection in the background Note: Can use the datasource name in the action, if available – as shown on next page. Otherwise, have to specify direct database and driver locations. Accessing a database directly from JSP page

Accessing a database from JSP with a Data source name <sql:setDataSource var=“productsdb" driver=“sun.jdbc.odbc.JdbcOdbcDriver" url="jdbc:odbc:products” user = “cindy” password = “DIT” scope = “session” datasource =.. /> Can specify username/password - optional DSN setDataSource tag has seven attributes: Will use this name in any other SQL statements To access the Db

Note: IF issue in setting up DSN (e.g. permissions problem in Labs).. Have to specify the database more specifically within the tag <sql:setDataSource var="shopDb" scope = "session" driver = "sun.jdbc.odbc.JdbcOdbcDriver" url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:\\Assignment\Shopping.mdb" /> Accessing a database from JSP (without a DSN) Instead of the DSN, have to enter in exact URL required for that database.. Including full path to the database

Querying a database To query a database… just use the sql: query tag Example <sql:query var = “productResult” dataSource = “${productsdb}” SELECT * FROM Products WHERE ProductID = ? / Holds the value of to be transferred into the ? placeholder. Variable to hold query result Will return all rows from Products table with a product ID name same as that supplied in the product name parameter DSN as defined in the setDAtasource

Querying a Database Querying, where parameter value is already known (i.e. not passed in…) <sql:query var = “productResult” dataSource = “${productsdb}” SELECT * FROM Products WHERE ProductType = ‘grocery’ Note: DOESN’T use “ “. !

Querying a database: tag has 6 attributes dataSource sql maxRows startRows var scope (p 151 of specification) Name of datasource. Optional. Needed if setDataSource tag used SQL statement. Mandatory. unless specified as the body. Optional. Maximum # of rows to show in result. Default is all rows Optional. Mandatory. The name of the variable to store the result. Optional. The scope for the query results - page (default), request, session or application. Set this carefully if you want to carry query results through to another page

Scope of a query… A JSP page itemsearch.jsp queries a database for a list of items that can be added to a shopping cart The results of the query search will be displayed on another JSP page called results.jsp The scope of the query that is executed in itemsearch.jsp needs to be ‘request’. Otherwise, query results will have ‘disappeared’ when itemsearch.jsp has passed control to results.jsp (because default scope is ‘page’ for queries).

<sql:query var = “productResult” scope = “request” dataSource = “${productsdb}” SELECT * FROM Products WHERE ProductID = ? / Specify the scope of the query results if the results need to be available to the request, session or application. The default scope is page. Scope of a query…

Querying a database: Partial info Search engines, on-line catalogues often need to allow user to search a database using partial information e.g. First name begins with “A”, surname contains “mc” In SQL, use the LIKE keyword and wildcard characters (%, _) SQL Examples of partial searches Search * From Customers WHERE FirstName LIKE “Jon%” Search * from Customers WHERE LastName LIKE “Sm_th”

Querying a database: Partial info To implement in JSTL, need to just incorporate the LIKE keyword and the wildcard characters Example: < sql:query var = “nameResult” dataSource = “S{customerDb}” SELECT FirstName, LastName FROM Customers WHERE FirstName LIKE ? AND LastNAME LIKE ? / Will return all rows from Employee table where first name begins with firstName parameter and last name contains value of lastName parameter

In the example, saw that query result is put into a variable Processing result of a query < sql:query var = “nameResult” …. etc This variable will contains the results set (a set of rows) of the query This variable is of type Result ( javax.servlet.jsp.jstl.sql.Result class ) and has a number of properties that can be used to process the result When a query is run, need to be able to process the results e.g. to display rows back as a HTML table

Properties for Result interface rows rowCount columnNames limitByMaxRows rowsByIndex Processing result of a query Rows returned by the query (array of column names and values) Number of rows in the result Array of column names boolean. true if Result was truncated due to maxRows attribute Rows return by the query, as arrays (rows/columns) of indexes

Processing result of a query: example To display back a list of customer names in a HTML table as a result of previous query: < sql:query var = “nameResult” etc Want to display back on web page: First nameLast name JohnMurphy SylviaMcAllister TomJones etc Need to display column names, followed by row results… with appropriate HTML tags,, etc

First name / Last name / <c:forEach items = “${nameResult.rows}” var = “row” Processing result of a query: example Rows from nameResult Property “rows” is used Assign any variable name to access the columns

Query: Code sample – outputs all rows on a table to a html page <sql:setDataSource var="shopDb" scope = "session" driver = "sun.jdbc.odbc.JdbcOdbcDriver" url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:\\test\Labdb.mdb" />

<%-- Selects username and address details from user table for all rows --%> SELECT UserName, Address1 FROM Customers Sorry, there are no customers on the Here is the list of customers User name Address Query: Code sample – outputs all rows on a table

Query: Code sample – outputs all rows on a table

Updating a database To update database information, can use INSERT, UPDATE or DELETE Use the is used for any SQL statement that doesn’t return rows --  it is used for INSERT, UPDATE, DELETE specification on page 148 of jstl specificaiton document has three attributes: sql (= sql statement), var (for result) and scope Uses ? and to assign parameter values in same way as

Updating a database Reminder --- SQL statements are of the form:… INSERT INSERT INTO CUSTOMERS (customer_ID, name, phone) VALUES (5, “JOHN”, “875895”) UPDATE UPDATE CUSTOMERS SET NAME = “Robert” WHERE CUSTOMER_ID = 1 DELETE DELETE FROM CUSTOMERS WHERE CUSTOMER_ID = 2

INSERT To INSERT a new record on a table called Customers Example: INSERT INTO Customers (UserName, Password, FirstName, LastName,DateofBirth) VALUES (?, ?, ?, ?, ?) Table name Column names Column values

Place holders (?) for column values are filled up by request parameters (I.e. very unlikely to be hardcoded!) Request parameters are matched against the ?s in the order they appear Add in the datasource name into the statement INSERT

Note: setting a column that contains date or time – need to use a special tag action called because of JDBC API quirk (requires specific JDBC data and time types). Also, if database table contains columns that are numeric (e.g. INT, REAL etc), may need to use the action to convert a string request parameter Data conversion

UPDATE To update database row(s), simply use the UPDATE statement in the SQL statement example: to update password, firstname and lastname on the row(s) in the Customer table where userName matches that held in the username request parameter. UPDATE Customers SET Password = ?, FirstName = ? LastNAme = ? WHERE UserName = ?

DELETE To update database row(s), simply use the UPDATE statement in the SQL statement example: To delete all rows from the Customer table where the username matches that held in the userName request parameter. DELETE FROM Customers WHERE UserName = ?,

Example of a simple search application that allows a user to search for an employee using a form (search.html). The search is processed by find.jsp, and presented back by list.jsp** ** Separates presentation from business logic/request processing

Sample code: find.jsp taglib prefix="sql" uri=" %> <sql:setDataSource var="empDb" scope = "session" driver = "sun.jdbc.odbc.JdbcOdbcDriver" url = "jdbc:odbc:employeedb" /> SELECT * FROM Employees WHERE FirstName LIKE ? AND LastName LIKE ? AND Department LIKE ? ORDER BY LastName connect to the database with appropriate driver Results of query must be available during the full request (in order to send result on to another page) Forward controL to list.jsp to display results

Sample code – search.html Search in Employee Database Please enter information about the employee you're looking for. You can use partial information in all fields. First Name: Last Name: … ETC ETC….. rest of form Calls find.jsp

List.jsp displays the rows found. If not row found, displays an error

Sample code – list.jsp Search Result Sorry, no employees were found. The following employees were found: Last Name First Name Department The name of the query

Sample code – list.jsp The name used by the developer to access the contents of each row. The used as row.LastName… etc

Common errors Not specifying the datasource in your SQL command (get “database null” error in Apache when running) Using wrong number of parameters in SQL action When Specifying the dataSource name in a SQL statement, need to put it as an expression in ${ }... otherwise, it will take the exact name in the “ “ and use it. Get an error, no suitable driver if you do this wrong. Scope: Make sure the scope on the SQL statement is correct, so that the connection or SQL statement results carry through to the required pages.

Tags used

Database access using JSLT Usually used for simple applications Can use java beans or servlets for database access for more complex applications

Info on JSTL Sun tutorial. Chapter 14 is on JSTL at: ml Contains examples Also, Sun’s JSTL 1.0 tag specification on distrib. Good for definition of each tag. Poor on examples