Web-based Database Development IS 465 Min Song. Three-Tier Architecture Oracle/MySQL DB Server Apache Tomcat App Server Microsoft Internet Explorer HTML.

Slides:



Advertisements
Similar presentations
19 augustus 2003augustus 2003 JSP-2. BICT 2JDBC BICT 3Install MySQL Download MySQL daemon – Free – Windows version… Start Daemon – Mysqld-nt.exe Download.
Advertisements

Basic JDBC Celsina Bignoli What is JDBC Industry standard for database- connectivity between the Java language and a wide range of.
JDBC. Java Database Connectivity (JDBC) Use the java.sql package to query and update the database. JDBC is an API that allows java to communicate with.
15-Jun-15 JDBC. JDBC is a Sun trademark It is often taken to stand for Java Database Connectivity Java is very standardized, but there are many versions.
1 JDBC Java Database Connectivity. 2 c.pdf
Object Oriented Programming Java Java’s JDBC Allows access to any ANSI SQL-2 DBMS Does its work in terms of SQL The JDBC has classes that represent:
JDBC Overview Autumn 2001 Lecturer: C. DeJong. Relational Databases widespread use used via SQL (Structured Query Language) freely available powerful.
Java Database Connectivity (JDBC) java.sql package to query and update the database. JDBC is an API that allows java to communicate with a database server.
Three-Tier Architecture Oracle DB Server Apache Tomcat App Server Microsoft Internet Explorer HTML Tuples HTTP Requests JDBC Requests Java Server Pages.
TUTORIAL (1) Software installation Written by: Eng. Ahmed Mohamed Abdel Ghafar, Edited by Eng. Muhammed Hammad, Eng. Hamdy Soltan & Eng. Osama Talaat.
Java MS Access database connectivity Follow these steps: 1)Go to the start->Control Panel->Administrative Tools- > data sources. 2)Click Add button and.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
1 CSC 440 Database Management Systems JDBC This presentation uses slides and lecture notes available from
1 Java Database Connection (JDBC) There are many industrial-strength DBMS's commercially available in the market. Oracle, DB2, and Sybase are just a few.
CS178 Database Management “JDBC”. What is JDBC ? JDBC stands for “Java DataBase Connectivity” The standard interface for communication between a Java.
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.
 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(1/25) Database Programming with JDBC Keith Vander Linden.
MySQL, Java, and JDBC CSE 3330 Southern Methodist University.
JDBC Tutorial MIE456 - Information Systems Infrastructure II Vinod Muthusamy November 4, 2004.
JDBC (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
JAVA Database Access. JDBC The Java Database Connectivity (JDBC) API is the industry standard for database- independent connectivity between the Java.
VICTORIA UNIVERSITY OF WELLINGTON Te Whare Wananga o te Upoko o te Ika a Maui COMP 302 Database Systems Java Data Base Connectivity Lecturer Dr Pavle Mogin.
Servlets Database Access. Agenda:  Setup Java Environment  Install Database  Install Database Drivers  Create Table and add records  Accessing a.
JDBC Java and Databases, including Postgress. JDBC l Developed by Industry leaders l Three main goals: –JDBC should be an SQL-level API –JDBC should capitalize.
CS 160: Software Engineering October 1 Class Meeting Department of Computer Science San Jose State University Fall 2014 Instructor: Ron Mak
JDBC. JDBC stands for Java Data Base Connectivity. JDBC is different from ODBC in that – JDBC is written in Java (hence is platform independent, object.
JDBC Java and Databases. RHS – SOC 2 JDBC JDBC – Java DataBase Connectivity An API (i.e. a set of classes and methods), for working with databases in.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
JSP program that interacts with HTML form & Access Data Base.
COMP201 Java Programming Topic 15: Database Connectivity JDBC Reading: Chapter 4, Volume 2.
Copyright  Oracle Corporation, All rights reserved. 6 Accessing a Database Using the JDBC API.
Chapter 25 Databases. Chapter Scope Database concepts Tables and queries SQL statements Managing data in a database Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25.
Domain Driven Web Development With WebJinn Sergei Kojarski College of Computer & Information Science Northeastern University joint work with David H. Lorenz.
JDBC Database Programming in Java Prepared by., Mrs.S.Amudha AP/SWE.
JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.
EXAMPLE I An application showing JDBC access to Cloudscape.
Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate.
16 Java Database Connectivity. 2 Understand the JDBC Understand the steps of the JDBC: 1.) Importing packages 2.) Opening a connection to a database 3.)
JDBC and SQLJ CIS 612 Spring JDBC JDBC is an API that enables database access from Java programs JDBC for DB access provides ◦ Portability across.
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.
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
Basics of JDBC.
1 JDBC: Part II Road Map Using Prepared Statements –Statements v. Prepared Statements –Using Prepared Statements Database Joins Using Database Transactions.
JDBC (Java Database Connectivity)
JDBC Java DataBase Connectivity. Loading the driver import java.sql.*... Class.forName("org.postgresql.Driver")‏
Web Programming Assistant Professor Xiaozhong Liu
JDBC Java and Databases. SWC – JDBC JDBC – Java DataBase Connectivity An API (i.e. a set of classes and methods), for working with databases in.
1 JDBC – Java Database Connectivity CS , Spring 2010.
1 Download current version of Tomcat from: g/tomcat/ g/tomcat/ Install it in: C:\Program Files\Apache.
JDBC I IS Why do we have databases?
Using Oracle JDBC How to Run JDBC on Your Account Communication Mechanism Using Metadata Building a Database Auto Commit v.s Atomic Transaction.
CS422 Principles of Database Systems JDBC and Embedded SQL Chengyu Sun California State University, Los Angeles.
JDBC.
1. Writing a Java program to connect to SQL Server 2008 and Create a table Populate the table (insert data) Perform queries to retrieve information from.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
CS3220 Web and Internet Programming Database Access with JDBC
Java Access to RDB Relational databases (RDBs) dominate today, due to:
1st Semester, 2017 Sanghyun Park
JDBC 15-Apr-18.
JDBC – Java Database Connectivity
CS320 Web and Internet Programming Database Access with JDBC
Advanced Web Automation Using Selenium
JDBC 21-Aug-18.
HW#4 Making Simple BBS Using JDBC
JDBC 15-Nov-18.
Interacting with Database
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Java Chapter 6 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Web-based Database Development IS 465 Min Song

Three-Tier Architecture Oracle/MySQL DB Server Apache Tomcat App Server Microsoft Internet Explorer HTML Tuples HTTP Requests JDBC Requests Java Server Pages (JSPs) your server Your PC Any PC

Data Entry Forms

Java Database Connectivity (JDBC)

Instruction for Building Web-based Database in Java Tomcat 6.0 or above – – From the above download site, choose Binary Distribution -> Core -> Zip Unzip the package to C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps Start Tomcat by executing tomcat6w in C:\Program Files\Apache Software Foundation\Tomcat 6.0\bin Open the internet browser and type If you see the tomcat on the upper left corner, you are successful so far.

Download mysql server at tml and install it onto your computer tml Download a sample DB from my home page Create a database in mysql as follows:

Shell > mysql –u root –p mysql> CREATE DATABASE world; mysql> USE world; mysql> SOURCE world.sql; mysql> SHOW TABLES;

Go to the following url: Note: You need to modify configuration files and properties file such as sqldb.xml and build.properties

Data Base Connectivity From JAVA package edu.njit.is465; import java.sql.Connection; // Java’s interface to SQL import java.sql.DriverManager; // Loads the appropriate SQL driver import java.sql.SQLException; // Handles errors from the database import java.util.Properties; // Configuration file to load the //db.properties file import java.util.logging.Level; // Logs information import java.util.logging.Logger; // Logs information /** * Base class for those that use a database connection * */ public abstract class DatabaseConnection { protected final Logger logger; protected Connection connect = null;

import java.sql.*; class JdbcTest { public static void main (String args []) throws SQLException { // Load Oracle driver DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver()); // Connect to the local database Connection conn = DriverManager.getConnection "scott", "tiger"); JDBC

// Query the student names Statement stmt = conn.createStatement (); ResultSet rset = stmt.executeQuery ("SELECT name FROM Student"); // Print the name out //name is the 2 nd attribute of Student while (rset.next ()) System.out.println (rset.getString (2)); //close the result set, statement, and the connection rset.close(); stmt.close(); conn.close();

PreparedStatement Object If you want to execute a Statement object many times, it will normally reduce execution time to use a PreparedStatement object instead. PreparedStatement updateStud = conn.prepareStatement( "UPDATE Student SET name = ? WHERE lastname LIKE ?"); updateStud.setString(1, “John”); updateStud.setString(2, “Smith”); updateStud.executeUpdate();

PreparedStatement Object the following two code fragments accomplish the same thing: Code Fragment 1: String updateString = "UPDATE COFFEES SET SALES = 75 " + "WHERE COF_NAME LIKE 'Colombian'"; stmt.executeUpdate(updateString); Code Fragment 2: PreparedStatement updateSales = con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ? "); updateSales.setInt(1, 75); updateSales.setString(2, "Colombian"); updateSales.executeUpdate():

int getInt(int columnIndex) Retrieves the value of the designated column in the current row of this ResultSet object as an int in the Java programming language. int getInt(String columnName) String getString(int columnIndex) String getString(String columnName)

Using Transactions When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. conn.setAutoCommit(false);.... transaction... con.commit(); con.setAutoCommit(true);

Using Transactions example con.setAutoCommit(false); PreparedStatement updateSales = con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?"); updateSales.setInt(1, 50); updateSales.setString(2, "Colombian"); updateSales.executeUpdate(); PreparedStatement updateTotal = con.prepareStatement( "UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?"); updateTotal.setInt(1, 50); updateTotal.setString(2, "Colombian"); updateTotal.executeUpdate(); con.commit(); con.setAutoCommit(true);

Retrieving Exceptions JDBC lets you see the warnings and exceptions generated by your DBMS and by the Java compiler. To see exceptions, you can have a catch block print them out. For example, the following two catch blocks from the sample code print out a message explaining the exception: try { // Code that could generate an exception goes here. // If an exception is generated, the catch block below // will print out information about it. } catch(SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); }

JSP Syntax Comment – Expression – Scriplet – Include –

Entry Form - First Attempt

Data Entry Menu Courses Classes Students Menu HTML Code

Entry Form - First Attempt Open connection code Statement code Presentation code Close connection code JSP Code

Entry Form - First Attempt <% try { // Load Oracle Driver class file DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver()); // Make a connection to the Oracle datasource Connection conn = DriverManager.getConnection “user", “pass"); %> Open Connectivity Code

Entry Form - First Attempt <% // Create the statement Statement statement = conn.createStatement(); // Use the statement to SELECT the student attributes // FROM the Student table. ResultSet rs = statement.executeQuery ("SELECT * FROM Student"); %> Statement Code

Entry Form - First Attempt SSN First Last College <% // Iterate over the ResultSet while ( rs.next() ) { %> Iteration Code <% } %> Presentation Code

Entry Form - First Attempt

Iteration Code

Entry Form - First Attempt <% // Close the ResultSet rs.close(); // Close the Statement statement.close(); // Close the Connection conn.close(); } catch (SQLException sqle) { out.println(sqle.getMessage()); } catch (Exception e) { out.println(e.getMessage()); } %> Close Connectivity Code

Entry Form - Second Attempt

Open connection code Insertion Code Statement code Presentation code Close connection code JSP Code

Entry Form - Second Attempt // Check if an insertion is requested String action = request.getParameter("action"); if (action != null && action.equals("insert")) { conn.setAutoCommit(false); // Create the prepared statement and use it to // INSERT the student attrs INTO the Student table. PreparedStatement pstmt = conn.prepareStatement( ("INSERT INTO Student VALUES (?, ?, ?, ?, ?)")); pstmt.setInt(1,Integer.parseInt(request.getParameter("SSN"))); pstmt.setString(2, request.getParameter("ID")); … pstmt.executeUpdate(); conn.commit(); conn.setAutoCommit(true); } Insertion Code

Entry Form - Second Attempt SSN First Last College Insert Form Code <% // Iterate over the ResultSet while ( rs.next() ) { %> Iteration Code <% } %> Presentation Code

Entry Form - Second Attempt Insert Form Code

Entry Form - Third Attempt

Open connection code Insertion Code Update Code Delete Code Statement code Presentation code Close connection code JSP Code

Entry Form - Third Attempt // Check if an update is requested if (action != null && action.equals("update")) { conn.setAutoCommit(false); // Create the prepared statement and use it to // UPDATE the student attributes in the Student table. PreparedStatement pstatement = conn.prepareStatement( "UPDATE Student SET ID = ?, FIRSTNAME = ?, " + "LASTNAME = ?, COLLEGE = ? WHERE SSN = ?"); pstatement.setString(1, request.getParameter("ID")); pstatement.setString(2, request.getParameter("FIRSTNAME")); … int rowCount = pstatement.executeUpdate(); conn.setAutoCommit(false); conn.setAutoCommit(true); } Update Code

Entry Form - Third Attempt // Check if a delete is requested if (action != null && action.equals("delete")) { conn.setAutoCommit(false); // Create the prepared statement and use it to // DELETE the student FROM the Student table. PreparedStatement pstmt = conn.prepareStatement( "DELETE FROM Student WHERE SSN = ?"); pstmt.setInt(1, Integer.parseInt(request.getParameter("SSN"))); int rowCount = pstmt.executeUpdate(); conn.setAutoCommit(false); conn.setAutoCommit(true); } Delete Code

Entry Form - Third Attempt SSN First Last College Insert Form Code <% // Iterate over the ResultSet while ( rs.next() ) { %> Iteration Code <% } %> Presentation Code

Entry Form - Third Attempt " name="SSN"> " name="ID"> … " name="SSN"> Iteration Code

Data Base Connectivity From JAVA public DatabaseConnection() throws Exception { logger = Logger.getLogger(this.getClass().getName()); Properties props = new Properties(); try { props.load(getClass().getResourceAsStream("db.properties")); final String driver = props.getProperty("driver"); final String url = props.getProperty("url"); final String user = props.getProperty("user"); final String pass = props.getProperty("pass"); Class.forName(driver).newInstance(); connect = DriverManager.getConnection(url, user, pass); } catch (Exception ex) { logger.log(Level.SEVERE, "Unable to create database connection", ex); throw new Exception("Unable to create database connection", ex); }

Data Base Connectivity From JAVA Driver specifies which backend database system to use In this case, we need a mySQL driver since the database is mySQL The URL specifies the location of the database as well as which database within mySQL to use db.properties file driver = com.mysql.jdbc.Driver url = jdbc:mysql://landsend.cs.drexel.edu/scheduler user = jsalvage pass = dbwiz

Data Base Connectivity From JAVA When an object goes out of scope it is important to close the connection. protected void finalize() { if (connect != null) { try { connect.close(); connect = null; } catch (SQLException ex) { logger.log(Level.SEVERE, "Unable to close database connection", ex); }

Data Base Connectivity From JAVA /* * DatabaseCourseManager.java * */ package edu.njit.is465; import java.sql.PreparedStatement; //Executes a SQL statement import java.sql.ResultSet; //Stores the rows returned from the query import java.sql.SQLException;//Handles errors import java.util.ArrayList;//Dynamic structure import java.util.List;//Interface to an ArrayList import java.util.logging.Level; Used to log errors /** * Database backed course manager * */ public class DatabaseCourseManager extends DatabaseConnection implements CourseManager {

Data Base Connectivity From JAVA ADDING A RECORD TO THE DATABASE Example: AddCourse A course contains: Department Name Department Number Number of Credits Name Description Therefore, the insert statement will contain five values. In it’s most basic form, a SQL INSERT statement has the following syntax: INSERT INTO TableName VALUES (list of values) This form of SQL INSERT requires the knowledge of the order of the fields in the table. The SQL table was created in the order the fields are listed above. Therefore, we can perform a SQL insert by listing the values in their proper place. Java allows this to be done without a lot of fancy string manipulation if you use the PreparedStatement object. Observe the following code which associates each value to be inserted with the proper question mark. One huge benefit to using the PreparedStatement instead of building the string manually, is it handles any special characters that would need to be escaped. i.e. double quote. In addition, it will prevent SQL code from inadvertently being executed, but that is an advanced topic.

Data Base Connectivity From JAVA /* edu.njit.is465.CourseManager#addCourse(edu.njit.is465.Course) */ public void addCourse(final Course course) throws SchedulerException { try { final PreparedStatement stm = connect.prepareStatement( "INSERT INTO Course VALUES(?, ?, ?, ?, ?)"); stm.setString(1, course.getDepartment()); stm.setInt(2, course.getNumber()); stm.setInt(3, course.getCredits()); stm.setString(4, course.getName()); stm.setString(5, course.getDescription()); int n = stm.executeUpdate(); stm.close(); if (n != 1) throw new SchedulerException("Unable to add course"); } catch (SQLException ex) { logger.log(Level.SEVERE, "addStudent", ex); throw new SchedulerException("Unable to add course", ex); } Executing the SQL command is simply a matter of calling the executeUpdate method of the PreparedStatement object.

Data Base Connectivity From JAVA RETRIEVING RECORDS FROM A DATABASE Example: getAllCourses We need to select data from the database and return it into a structure Java can understand. In it’s most basic form, a SQL SELECT statement has the following syntax: SELECT * FROM TableName ORDER BY ListOfFields The ORDER BY clause is optional, but will allow the results to be sorted by the fields we list after the keywords ORDER BY. Again we will use the PreparedStatement to hold the SQL command. The results of the query will be stored in a ResultSet object and then each record will be added to our courses object.

Data Base Connectivity From JAVA /* edu.njit.is465.CourseManager#getAllCourses() */ public Course[] getAllCourses() { try { final PreparedStatement stm = connect.prepareStatement( "SELECT * FROM Course ORDER BY dept, num"); final ResultSet result = stm.executeQuery(); final List courses = new ArrayList (); while (result.next()) courses.add(toCourse(result)); result.close(); stm.close(); return courses.toArray(new Course[0]); } catch (SQLException ex) { logger.log(Level.SEVERE, "getAllCourses", ex); return new Course[0]; }

Data Base Connectivity From JAVA RETRIEVING RECORDS FROM A DATABASE WITH A CONDITION Example: getCourse We need to add a selection criteria to our SQL statement so only a specific of courses is returned. In it’s most complex form, a SQL SELECT statement has the following syntax: SELECT * FROM TableName WHERE Field1 = value1 and Field2 = value2 The WHERE clause is optional, and allows the results to filtered based upon the selection criteria you list. Again we will use the PreparedStatement to hold the SQL command. The results of the query will be stored in a ResultSet object and the single record will be added to our course object.

Data Base Connectivity From JAVA /* edu.njit.is465.CourseManager#getCourse(java.lang.String, int) */ public Course getCourse(final String dept, int num) { Course course = null; try { final PreparedStatement stm = connect.prepareStatement( "SELECT * FROM Course WHERE dept = ? AND num = ?"); stm.setString(1, dept); stm.setInt(2, num); final ResultSet result = stm.executeQuery(); if (result.next()) course = toCourse(result); result.close(); stm.close(); } catch (SQLException ex) { logger.log(Level.SEVERE, "getCourse", ex); } return course; }

Data Base Connectivity From JAVA /* edu.njit.465.CourseManager#removeCourse(java.lang.String, int) */ public void removeCourse(final String dept, int num) throws SchedulerException { try { final PreparedStatement stm = connect.prepareStatement( "DELETE FROM Course WHERE dept = ? AND num = ?"); stm.setString(1, dept); stm.setInt(2, num); stm.executeUpdate(); stm.close(); } catch (SQLException ex) { logger.log(Level.SEVERE, "removeCourse", ex); throw new SchedulerException(ex); }

Data Base Connectivity From JAVA /* edu.njit.is465.CourseManager#updateCourse(edu.njit.is465.Course) */ public void updateCourse(final Course course) throws SchedulerException { try { final PreparedStatement stm = connect.prepareStatement( "UPDATE Course SET credits = ?, name = ?, description = ?" + " WHERE dept = ? AND name = ?"); stm.setInt(1, course.getCredits()); stm.setString(2, course.getName()); stm.setString(3, course.getDescription()); stm.setString(4, course.getDepartment()); stm.setInt(5, course.getNumber()); stm.executeUpdate(); stm.close(); } catch (SQLException ex) { logger.log(Level.SEVERE, "updateCourse", ex); throw new SchedulerException(ex); } private Course toCourse(final ResultSet result) throws SQLException { final String dept = result.getString("dept"); final int num = result.getInt("num"); final Course course = new Course(dept, num); course.setCredits(result.getInt("credits")); course.setName(result.getString("name")); course.setDescription(result.getString("description")); return course; }