SlideShare ist ein Scribd-Unternehmen logo
1 von 50
Web-based Database
Development
IS 465
Min Song
Three-Tier Architecture
Microsoft
Internet
Explorer

Located
@ Any PC
HTTP
Requests
Located
@ Your PC

Apache Tomcat Java Server
App Server
Pages (JSPs)
JDBC
Requests

Located
@ your server

HTML

Tuples

Oracle/MySQL
DB Server
Data Entry Forms
Java Database Connectivity (JDBC)
Instruction for Building Web-based
Database in Java
• Tomcat 6.0 or above
– http://tomcat.apache.org/download-60.cgi
– From the above download site, choose Binary Distribution
-> Core -> Zip

• Unzip the package to C:Program FilesApache
Software FoundationTomcat 6.0webapps
• Start Tomcat by executing tomcat6w in C:Program
FilesApache Software FoundationTomcat 6.0bin
• Open the internet browser and type
http://localhost:8080/. If you see the tomcat on the
upper left corner, you are successful so far.
• Download mysql server at
http://dev.mysql.com/downloads/mysql/5.1.html
and install it onto your computer
• 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:
http://localhost/world_db/index.jsp
• 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
import
import
import

java.sql.Connection; // Java’s interface to SQL
java.sql.DriverManager; // Loads the appropriate SQL driver
java.sql.SQLException; // Handles errors from the database
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
*
* @version 1.0
* @since 1.0
*/
public abstract class DatabaseConnection
{
protected final Logger logger;
protected Connection connect = null;
JDBC
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
("jdbc:oracle:thin:@myhost:1521:ORCL","scott", "tiger");
// Query the student names
Statement stmt = conn.createStatement ();
ResultSet rset = stmt.executeQuery ("SELECT name FROM
Student");
// Print the name out
//name is the 2nd attribute of Student
while (rset.next ())
System.out.println (rset.getString (1)); 
//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
– <%-- Comment --%>

• Expression
– <%= java expression %>

• Scriplet
– <% java code fragment %>

• Include
– <jsp:include page="relativeURL" />
Entry Form - First Attempt
Entry Form - First Attempt
Menu HTML Code

<b>Data Entry Menu</b>
<ul>
<li>
<a href="courses.jsp">Courses<a>
</li>
<li>
<a href="classes.jsp">Classes<a>
</li>
<li>
<a href="students.jsp">Students<a>
</li>
</ul>
Entry Form - First Attempt
JSP Code
<html>
<body>
<table>
<tr>
<td>
<jsp:include page="menu.html" />
</td>
<td>
Open connection code
Statement code
Presentation code
Close connection code
</td>
</tr>
</table>
</body>
</html>
Entry Form - First Attempt
Open Connectivity Code
<%-- Set the scripting language to java and --%>
<%-- import the java.sql package --%>
<%@ page language="java" import="java.sql.*" %>
<%
try {
// Load Oracle Driver class file
DriverManager.registerDriver
(new oracle.jdbc.driver.OracleDriver());
// Make a connection to the Oracle datasource
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@feast.ucsd.edu:1521:source",
“user", “pass");
%>
Entry Form - First Attempt
Statement Code
<%
// 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");
%>
Entry Form - First Attempt
Presentation Code
<table>
<tr>
<th>SSN</th>
<th>First</th>
<th>Last</th>
<th>College</th>
</tr>
<%
// Iterate over the ResultSet
while ( rs.next() ) {
%>
Iteration Code
<%
}
%>
</table>
Entry Form - First Attempt
Entry Form - First Attempt
Iteration Code
<tr>
<%-- Get the SSN, which is a number --%>
<td><%= rs.getInt("SSN") %></td>
<%-- Get the ID --%>
<td><%= rs.getString("ID") %></td>
<%-- Get the FIRSTNAME --%>
<td><%= rs.getString("FIRSTNAME") %></td>
<%-- Get the LASTNAME --%>
<td><%= rs.getString("LASTNAME") %></td>
<%-- Get the COLLEGE --%>
<td><%= rs.getString("COLLEGE") %></td>
</tr>
Entry Form - First Attempt
Close Connectivity Code
<%
// 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());
}
%>
Entry Form - Second Attempt
Entry Form - Second Attempt
JSP Code
<html>
<body>
<table>
<tr>
<td>
Open connection code
Insertion Code
Statement code
Presentation code
Close connection code
</td>
</tr>
</table>
</body>
</html>
Entry Form - Second Attempt
Insertion Code
// 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);
}
Entry Form - Second Attempt
Presentation Code
<table>
<tr>
<th>SSN</th>
<th>First</th>
<th>Last</th>
<th>College</th>
</tr>
Insert Form Code
<%
// Iterate over the ResultSet
while ( rs.next() ) {
%>
Iteration Code
<%
}
%>
</table>
Entry Form - Second Attempt
Insert Form Code
<tr>
<form action="students.jsp" method="get">
<input type="hidden" value="insert" name="action">
<th><input value="" name="SSN" size="10"></th>
<th><input value="" name="ID" size="10"></th>
<th><input value="" name="FIRSTNAME" size="15"></th>
<th><input value="" name="LASTNAME" size="15"></th>
<th><input value="" name="COLLEGE" size="15"></th>
<th><input type="submit" value="Insert"></th>
</form>
</tr>
Entry Form - Third Attempt
Entry Form - Third Attempt
JSP Code
<html>
<body>
<table>
<tr>
<td>
Open connection code
Insertion Code
Update Code
Delete Code
Statement code
Presentation code
Close connection code
</td>
</tr>
</table>
</body>
</html>
Entry Form - Third Attempt
Update Code
// 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);
}
Entry Form - Third Attempt
Delete Code
// 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);
}
Entry Form - Third Attempt
Presentation Code
<table>
<tr>
<th>SSN</th>
<th>First</th>
<th>Last</th>
<th>College</th>
</tr>
Insert Form Code
<%
// Iterate over the ResultSet
while ( rs.next() ) {
%>
Iteration Code
<%
}
%>
</table>
Entry Form - Third Attempt
Iteration Code
<tr>
<form action="students.jsp" method="get">
<input type="hidden" value="update" name="action">
<td><input value="<%= rs.getInt("SSN") %>" name="SSN"></td>
<td><input value="<%= rs.getString("ID") %>" name="ID"></td>
…
<td><input type="submit" value="Update"></td>
</form>
<form action="students2.jsp" method="get">
<input type="hidden" value="delete" name="action">
<input type="hidden" value="<%= rs.getInt("SSN") %>"
name="SSN">
<td><input type="submit" value="Delete"></td>
</form>
</tr>
Data Base Connectivity From JAVA
public DatabaseConnection() throws Exception
{
logger = Logger.getLogger(this.getClass().getName());

connection",

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
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
import
import
import
import
import

java.sql.PreparedStatement; //Executes a SQL statement
java.sql.ResultSet; //Stores the rows returned from the query
java.sql.SQLException;//Handles errors
java.util.ArrayList;//Dynamic structure
java.util.List;//Interface to an ArrayList
java.util.logging.Level; Used to log errors

/**
* Database backed course manager
* * @version 1.0
* @since 1.0
*/
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
/*
* @see 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
/*
* @see 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<Course> courses = new ArrayList<Course>();
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
/*
* @see 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
/*
* @see 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
/*

* @see 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;
}

Weitere ähnliche Inhalte

Was ist angesagt?

#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Advanced Sql Injection ENG
Advanced Sql Injection ENGAdvanced Sql Injection ENG
Advanced Sql Injection ENGDmitry Evteev
 
SQL Injection: complete walkthrough (not only) for PHP developers
SQL Injection: complete walkthrough (not only) for PHP developersSQL Injection: complete walkthrough (not only) for PHP developers
SQL Injection: complete walkthrough (not only) for PHP developersKrzysztof Kotowicz
 
Grain final border one
Grain final border oneGrain final border one
Grain final border oneAshish Gupta
 
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Bt0083 server side programing 2
Bt0083 server side programing  2Bt0083 server side programing  2
Bt0083 server side programing 2Techglyphs
 
Spring Framework Petclinic sample application
Spring Framework Petclinic sample applicationSpring Framework Petclinic sample application
Spring Framework Petclinic sample applicationAntoine Rey
 
Advanced SQL Injection: Attacks
Advanced SQL Injection: Attacks Advanced SQL Injection: Attacks
Advanced SQL Injection: Attacks Nuno Loureiro
 
Refactoring Jdbc Programming
Refactoring Jdbc ProgrammingRefactoring Jdbc Programming
Refactoring Jdbc Programmingchanwook Park
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
Advanced SQL Injection
Advanced SQL InjectionAdvanced SQL Injection
Advanced SQL Injectionamiable_indian
 
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2Naga Muruga
 
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...탑크리에듀(구로디지털단지역3번출구 2분거리)
 

Was ist angesagt? (20)

#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
 
Not so blind SQL Injection
Not so blind SQL InjectionNot so blind SQL Injection
Not so blind SQL Injection
 
Advanced Sql Injection ENG
Advanced Sql Injection ENGAdvanced Sql Injection ENG
Advanced Sql Injection ENG
 
SQL Injection: complete walkthrough (not only) for PHP developers
SQL Injection: complete walkthrough (not only) for PHP developersSQL Injection: complete walkthrough (not only) for PHP developers
SQL Injection: complete walkthrough (not only) for PHP developers
 
Testy integracyjne
Testy integracyjneTesty integracyjne
Testy integracyjne
 
Grain final border one
Grain final border oneGrain final border one
Grain final border one
 
Java Programming - 08 java threading
Java Programming - 08 java threadingJava Programming - 08 java threading
Java Programming - 08 java threading
 
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
 
Bt0083 server side programing 2
Bt0083 server side programing  2Bt0083 server side programing  2
Bt0083 server side programing 2
 
Spring Framework Petclinic sample application
Spring Framework Petclinic sample applicationSpring Framework Petclinic sample application
Spring Framework Petclinic sample application
 
Advanced SQL Injection: Attacks
Advanced SQL Injection: Attacks Advanced SQL Injection: Attacks
Advanced SQL Injection: Attacks
 
Refactoring Jdbc Programming
Refactoring Jdbc ProgrammingRefactoring Jdbc Programming
Refactoring Jdbc Programming
 
Sql Injection Myths and Fallacies
Sql Injection Myths and FallaciesSql Injection Myths and Fallacies
Sql Injection Myths and Fallacies
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Advanced SQL Injection
Advanced SQL InjectionAdvanced SQL Injection
Advanced SQL Injection
 
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
 
Sql full tutorial
Sql full tutorialSql full tutorial
Sql full tutorial
 
Sql injection
Sql injectionSql injection
Sql injection
 
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
 

Ähnlich wie Web based development

Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Zianed Hou
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Databasejitendral
 
JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.pptSwapnil Kale
 
General Principles of Web Security
General Principles of Web SecurityGeneral Principles of Web Security
General Principles of Web Securityjemond
 
การเข ยนโปรแกรมต ดต_อฐานข_อม_ล
การเข ยนโปรแกรมต ดต_อฐานข_อม_ลการเข ยนโปรแกรมต ดต_อฐานข_อม_ล
การเข ยนโปรแกรมต ดต_อฐานข_อม_ลBongza Naruk
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran TochAdil Jafri
 
Step By Step Guide For Buidling Simple Struts App
Step By Step Guide For Buidling Simple Struts AppStep By Step Guide For Buidling Simple Struts App
Step By Step Guide For Buidling Simple Struts AppSyed Shahul
 
Learning Java 4 – Swing, SQL, and Security API
Learning Java 4 – Swing, SQL, and Security APILearning Java 4 – Swing, SQL, and Security API
Learning Java 4 – Swing, SQL, and Security APIcaswenson
 
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)DK Lee
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingVisual Engineering
 
Silicon Valley CodeCamp 2008: High performance Ajax with ExtJS and ASP.NET
Silicon Valley CodeCamp 2008: High performance Ajax with ExtJS and ASP.NETSilicon Valley CodeCamp 2008: High performance Ajax with ExtJS and ASP.NET
Silicon Valley CodeCamp 2008: High performance Ajax with ExtJS and ASP.NETMats Bryntse
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeletonIram Ramrajkar
 

Ähnlich wie Web based development (20)

Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.ppt
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
General Principles of Web Security
General Principles of Web SecurityGeneral Principles of Web Security
General Principles of Web Security
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 
การเข ยนโปรแกรมต ดต_อฐานข_อม_ล
การเข ยนโปรแกรมต ดต_อฐานข_อม_ลการเข ยนโปรแกรมต ดต_อฐานข_อม_ล
การเข ยนโปรแกรมต ดต_อฐานข_อม_ล
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran Toch
 
Step By Step Guide For Buidling Simple Struts App
Step By Step Guide For Buidling Simple Struts AppStep By Step Guide For Buidling Simple Struts App
Step By Step Guide For Buidling Simple Struts App
 
Learning Java 4 – Swing, SQL, and Security API
Learning Java 4 – Swing, SQL, and Security APILearning Java 4 – Swing, SQL, and Security API
Learning Java 4 – Swing, SQL, and Security API
 
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
 
Lecture17
Lecture17Lecture17
Lecture17
 
Lab manual asp.net
Lab manual asp.netLab manual asp.net
Lab manual asp.net
 
Pl sql using_xml
Pl sql using_xmlPl sql using_xml
Pl sql using_xml
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
Silicon Valley CodeCamp 2008: High performance Ajax with ExtJS and ASP.NET
Silicon Valley CodeCamp 2008: High performance Ajax with ExtJS and ASP.NETSilicon Valley CodeCamp 2008: High performance Ajax with ExtJS and ASP.NET
Silicon Valley CodeCamp 2008: High performance Ajax with ExtJS and ASP.NET
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
 
Advance java
Advance javaAdvance java
Advance java
 

Mehr von Mumbai Academisc (20)

Non ieee java projects list
Non  ieee java projects list Non  ieee java projects list
Non ieee java projects list
 
Non ieee dot net projects list
Non  ieee dot net projects list Non  ieee dot net projects list
Non ieee dot net projects list
 
Ieee java projects list
Ieee java projects list Ieee java projects list
Ieee java projects list
 
Ieee 2014 java projects list
Ieee 2014 java projects list Ieee 2014 java projects list
Ieee 2014 java projects list
 
Ieee 2014 dot net projects list
Ieee 2014 dot net projects list Ieee 2014 dot net projects list
Ieee 2014 dot net projects list
 
Ieee 2013 java projects list
Ieee 2013 java projects list Ieee 2013 java projects list
Ieee 2013 java projects list
 
Ieee 2013 dot net projects list
Ieee 2013 dot net projects listIeee 2013 dot net projects list
Ieee 2013 dot net projects list
 
Ieee 2012 dot net projects list
Ieee 2012 dot net projects listIeee 2012 dot net projects list
Ieee 2012 dot net projects list
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Ejb notes
Ejb notesEjb notes
Ejb notes
 
Java web programming
Java web programmingJava web programming
Java web programming
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
 
J2ee project lists:-Mumbai Academics
J2ee project lists:-Mumbai AcademicsJ2ee project lists:-Mumbai Academics
J2ee project lists:-Mumbai Academics
 
Jdbc
JdbcJdbc
Jdbc
 
Java tutorial part 4
Java tutorial part 4Java tutorial part 4
Java tutorial part 4
 
Java tutorial part 3
Java tutorial part 3Java tutorial part 3
Java tutorial part 3
 
Java tutorial part 2
Java tutorial part 2Java tutorial part 2
Java tutorial part 2
 
Engineering
EngineeringEngineering
Engineering
 
Jsp
JspJsp
Jsp
 

Kürzlich hochgeladen

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxdhanalakshmis0310
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 

Kürzlich hochgeladen (20)

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 

Web based development

  • 2. Three-Tier Architecture Microsoft Internet Explorer Located @ Any PC HTTP Requests Located @ Your PC Apache Tomcat Java Server App Server Pages (JSPs) JDBC Requests Located @ your server HTML Tuples Oracle/MySQL DB Server
  • 5. Instruction for Building Web-based Database in Java • Tomcat 6.0 or above – http://tomcat.apache.org/download-60.cgi – From the above download site, choose Binary Distribution -> Core -> Zip • Unzip the package to C:Program FilesApache Software FoundationTomcat 6.0webapps • Start Tomcat by executing tomcat6w in C:Program FilesApache Software FoundationTomcat 6.0bin • Open the internet browser and type http://localhost:8080/. If you see the tomcat on the upper left corner, you are successful so far.
  • 6. • Download mysql server at http://dev.mysql.com/downloads/mysql/5.1.html and install it onto your computer • Download a sample DB from my home page • Create a database in mysql as follows:
  • 7. • • • • • Shell > mysql –u root –p mysql> CREATE DATABASE world; mysql> USE world; mysql> SOURCE world.sql; mysql> SHOW TABLES;
  • 8. • Go to the following url: http://localhost/world_db/index.jsp • Note: You need to modify configuration files and properties file such as sqldb.xml and build.properties
  • 9. Data Base Connectivity From JAVA package edu.njit.is465; import import import import java.sql.Connection; // Java’s interface to SQL java.sql.DriverManager; // Loads the appropriate SQL driver java.sql.SQLException; // Handles errors from the database 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 * * @version 1.0 * @since 1.0 */ public abstract class DatabaseConnection { protected final Logger logger; protected Connection connect = null;
  • 10. JDBC 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 ("jdbc:oracle:thin:@myhost:1521:ORCL","scott", "tiger");
  • 11. // Query the student names Statement stmt = conn.createStatement (); ResultSet rset = stmt.executeQuery ("SELECT name FROM Student"); // Print the name out //name is the 2nd attribute of Student while (rset.next ()) System.out.println (rset.getString (1));  //close the result set, statement, and the connection rset.close(); stmt.close(); conn.close();
  • 12. 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();
  • 13. 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():
  • 14. •  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)         
  • 15. 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);                  
  • 16. 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);     
  • 17. 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()); }
  • 18. JSP Syntax • Comment – <%-- Comment --%> • Expression – <%= java expression %> • Scriplet – <% java code fragment %> • Include – <jsp:include page="relativeURL" />
  • 19. Entry Form - First Attempt
  • 20. Entry Form - First Attempt Menu HTML Code <b>Data Entry Menu</b> <ul> <li> <a href="courses.jsp">Courses<a> </li> <li> <a href="classes.jsp">Classes<a> </li> <li> <a href="students.jsp">Students<a> </li> </ul>
  • 21. Entry Form - First Attempt JSP Code <html> <body> <table> <tr> <td> <jsp:include page="menu.html" /> </td> <td> Open connection code Statement code Presentation code Close connection code </td> </tr> </table> </body> </html>
  • 22. Entry Form - First Attempt Open Connectivity Code <%-- Set the scripting language to java and --%> <%-- import the java.sql package --%> <%@ page language="java" import="java.sql.*" %> <% try { // Load Oracle Driver class file DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver()); // Make a connection to the Oracle datasource Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@feast.ucsd.edu:1521:source", “user", “pass"); %>
  • 23. Entry Form - First Attempt Statement Code <% // 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"); %>
  • 24. Entry Form - First Attempt Presentation Code <table> <tr> <th>SSN</th> <th>First</th> <th>Last</th> <th>College</th> </tr> <% // Iterate over the ResultSet while ( rs.next() ) { %> Iteration Code <% } %> </table>
  • 25. Entry Form - First Attempt
  • 26. Entry Form - First Attempt Iteration Code <tr> <%-- Get the SSN, which is a number --%> <td><%= rs.getInt("SSN") %></td> <%-- Get the ID --%> <td><%= rs.getString("ID") %></td> <%-- Get the FIRSTNAME --%> <td><%= rs.getString("FIRSTNAME") %></td> <%-- Get the LASTNAME --%> <td><%= rs.getString("LASTNAME") %></td> <%-- Get the COLLEGE --%> <td><%= rs.getString("COLLEGE") %></td> </tr>
  • 27. Entry Form - First Attempt Close Connectivity Code <% // 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()); } %>
  • 28. Entry Form - Second Attempt
  • 29. Entry Form - Second Attempt JSP Code <html> <body> <table> <tr> <td> Open connection code Insertion Code Statement code Presentation code Close connection code </td> </tr> </table> </body> </html>
  • 30. Entry Form - Second Attempt Insertion Code // 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); }
  • 31. Entry Form - Second Attempt Presentation Code <table> <tr> <th>SSN</th> <th>First</th> <th>Last</th> <th>College</th> </tr> Insert Form Code <% // Iterate over the ResultSet while ( rs.next() ) { %> Iteration Code <% } %> </table>
  • 32. Entry Form - Second Attempt Insert Form Code <tr> <form action="students.jsp" method="get"> <input type="hidden" value="insert" name="action"> <th><input value="" name="SSN" size="10"></th> <th><input value="" name="ID" size="10"></th> <th><input value="" name="FIRSTNAME" size="15"></th> <th><input value="" name="LASTNAME" size="15"></th> <th><input value="" name="COLLEGE" size="15"></th> <th><input type="submit" value="Insert"></th> </form> </tr>
  • 33. Entry Form - Third Attempt
  • 34. Entry Form - Third Attempt JSP Code <html> <body> <table> <tr> <td> Open connection code Insertion Code Update Code Delete Code Statement code Presentation code Close connection code </td> </tr> </table> </body> </html>
  • 35. Entry Form - Third Attempt Update Code // 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); }
  • 36. Entry Form - Third Attempt Delete Code // 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); }
  • 37. Entry Form - Third Attempt Presentation Code <table> <tr> <th>SSN</th> <th>First</th> <th>Last</th> <th>College</th> </tr> Insert Form Code <% // Iterate over the ResultSet while ( rs.next() ) { %> Iteration Code <% } %> </table>
  • 38. Entry Form - Third Attempt Iteration Code <tr> <form action="students.jsp" method="get"> <input type="hidden" value="update" name="action"> <td><input value="<%= rs.getInt("SSN") %>" name="SSN"></td> <td><input value="<%= rs.getString("ID") %>" name="ID"></td> … <td><input type="submit" value="Update"></td> </form> <form action="students2.jsp" method="get"> <input type="hidden" value="delete" name="action"> <input type="hidden" value="<%= rs.getInt("SSN") %>" name="SSN"> <td><input type="submit" value="Delete"></td> </form> </tr>
  • 39. Data Base Connectivity From JAVA public DatabaseConnection() throws Exception { logger = Logger.getLogger(this.getClass().getName()); connection", 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 ex); throw new Exception("Unable to create database connection", } } ex);
  • 40. 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
  • 41. 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); } } } }
  • 42. Data Base Connectivity From JAVA /* * DatabaseCourseManager.java * */ package edu.njit.is465; import import import import import import java.sql.PreparedStatement; //Executes a SQL statement java.sql.ResultSet; //Stores the rows returned from the query java.sql.SQLException;//Handles errors java.util.ArrayList;//Dynamic structure java.util.List;//Interface to an ArrayList java.util.logging.Level; Used to log errors /** * Database backed course manager * * @version 1.0 * @since 1.0 */ public class DatabaseCourseManager extends DatabaseConnection implements CourseManager {
  • 43. 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.
  • 44. Data Base Connectivity From JAVA /* * @see 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.
  • 45. 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.
  • 46. Data Base Connectivity From JAVA /* * @see 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<Course> courses = new ArrayList<Course>(); 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]; } }
  • 47. 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.
  • 48. Data Base Connectivity From JAVA /* * @see 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; }
  • 49. Data Base Connectivity From JAVA /* * @see 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); } }
  • 50. Data Base Connectivity From JAVA /* * @see 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; }