Download Lab 3 Handout

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Extensible Storage Engine wikipedia , lookup

Oracle Database wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Microsoft Access wikipedia , lookup

Concurrency control wikipedia , lookup

Ingres (database) wikipedia , lookup

Functional Database Model wikipedia , lookup

Database wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Versant Object Database wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

SQL wikipedia , lookup

Relational model wikipedia , lookup

Clusterpoint wikipedia , lookup

Database model wikipedia , lookup

PL/SQL wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Transcript
CS281 Spring 2017
Lab Handout #3
DATABASE APPLICATION DEVELOPMENT
SQL in Application Code


SQL commands can be called from within a host language (e.g., C++ or Java) program.
o SQL statements can refer to host variables (including special variables used to
return status).
o Must include a statement to connect to the right database
Two main integration approaches:
o Embed SQL in the host language (Embedded SQL, SQLJ)
o Create special API to call SQL commands (JDBC)
1) Embedded SQL
Approach: Embed SQL in the host language.
 A preprocessor converts the SQL statements into special API calls.
 Then a regular compiler is used to compile the code.
Language constructs:
 Connecting to a database:
EXEC SQL CONNECT
 Declaring variables:
EXEC SQL BEGIN (END) DECLARE SECTION
 Statements:
EXEC SQL Statement;
 Variables:
 Two special “error” variables, one of them must be declared:
SQLCODE (long, is negative if an error has occurred)
SQLSTATE (char[6], predefined codes for common errors)
2) Database APIs: Alternative to embedding
Rather than modify compiler, add library with database calls (API)
o
o
o
o
Special standardized interface: procedures/objects
Pass SQL strings from language, presents result sets in a language-friendly way
Sun’s JDBC: Java API
Supposedly DBMS-neutral a “driver” traps the calls and translates them into
DBMSspecific code database can be across a network
o DBMS independent both at the source code and executable level.
JDBC architecture has four components:
o Application (initiates and terminates connections, submits SQL statements)
o Driver manager (load JDBC driver)
o Driver (connects to data source, transmits requests and returns/translates results and error
codes)
o Data source (processes SQL statements)
Steps to submit a database query:
o Load the JDBC driver
o Connect to the data source
o Execute SQL statements
We will go through an example to learn how to use JDBC:
Important Note-1: If you would like to download and use a database file (e.g., if you download
the database file of Homework 3), it is usually forbidden to edit the content of database. In such
cases, you cannot add, delete, or update the database via Java. To avoid this problem, right click
on the database file, select properties, and click on the button that allows to edit the file (the
following picture includes a sample case in Turkish).
Important Note-2:
The Oracle Sun's JDBC Driver, ODBC, connects to a MS Access file (*.mdb or *.accdb).
However, this driver is not supported after the release of JDK 8 (Java Development Kit v1.8).
Therefore, we can use a JDBC driver published by a third-party organization, namely HXTT
(www.hxtt.com)
If your JDK has a version of 1.8.x or later (if not, ignore this part and use the code in the
next page), you should first download HXTT Driver from
http://cs.bilkent.edu.tr/~ctoraman/cs281spring17/Access_JDBC30.jar
Then, configure the build path of your Java project by adding this external jar file (Explained in
http://oopbook.com/java-classpath-2/classpath-in-jcreator/).
Then, you should use the following code:
/********** Start of Example Code for JDK version 1.8.x or later*********************/
// Step 1: Include necessary Java packages
import java.sql.*;
//Following steps are in the main method:
try{
// Step 2: Load the corresponding JDBC driver for the data source you want to connect.
Class.forName("com.hxtt.sql.access.AccessDriver");
/* Step 3: We interact with a data source through sessions. Each connection identifies a
logical session. Connnections are specified through a JDBC URL in the following form:
jdbc:<subprotocol>:<otherParameters>
*/
String url = "jdbc:access:/c:/college.accdb";
String userId=””;
String password=””;
Connection con = DriverManager.getConnection(url, userId, password);
System.out.println("Successfully connected to the database!");
}
catch(ClassNotFoundException classEx) // this exception is caught if the driver is unknown
{
System.out.println("Class Not found exception" ); // Give the appropirate error here
}
catch(SQLException sqlEx) // this exception is caught if something is wrong with connection
{
System.out.println("\nError occured during getting the connection\n" + sqlEx);
}
If your JDK has a version that is earlier than 1.8 (e.g., JDK 1.4), then you should use the
following code:
/*********** Start of Example Code for JDK versions earlier than 1.8*******************/
// Step 1: Include necessary Java packages
import java.sql.*;
//Following steps are in the main method:
try{
// Step 2: Load the corresponding JDBC driver for the data source you want to connect.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
/* Step 3: We interact with a data source through sessions. Each connection identifies a
logical session. Connnections are specified through a JDBC URL in the following form:
jdbc:<subprotocol>:<otherParameters>
*/
String url = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};
DBQ=C:\\sample.accdb";
String userId=””;
String password=””;
Connection con = DriverManager.getConnection(url, userId, password);
System.out.println("Successfully connected to the database!");
}
catch(ClassNotFoundException classEx) // this exception is caught if the driver is unknown
{
System.out.println("Class Not found exception" ); // Give the appropirate error here
}
catch(SQLException sqlEx) // this exception is caught if something is wrong with connection
{
System.out.println("\nError occured during getting the connection\n" + sqlEx);
}
The following code segments work for all JDK versions:
// Step 4: Now, we want to create SQL statements. In JDBC, there are three different ways of
executing statements: Statement, PreparedStatement and Callable Statement.
// We can simply use a Statement for a query, and use ResultSet object to handle the query result.
// First, let’s declare and create a Statement object.
Statement selectStmt;
selectStmt = con.createStatement();
// Notice that we will handle the result by using a ResultSet object, similar to a cursor.
ResultSet rs;
// Execute the query
rs = selectStmt.executeQuery("SELECT * FROM employee");
// Now, you can read values from each tuple and so something with them
while(rs.next())
{
System.out.print(“Emp no:” + rs.getInt(1) +" ");
System.out.print(“Emp name:”+ rs.getString(2)+ " ");
…
}
// For a PreparedStatement, the structure is fixed but values of parameters are determined at the
run time.
// First, determine your query structure
String sql_string= "INSERT INTO employee VALUES (?,?,?,?,?,?,?,?,?)";
/ / create the prepared statement
PreparedStatement pstmt = con.prepareStatement (sql_string);
// Now, we instantiate the parameters with values
pstmt.clearParameters();
pstmt.setInt(1,100);
pstmt.setString(2, “john”);
pstmt.setString(3, “manager”);
// submit the query to the data source.
pstmt.executeUpdate();
// finally close statement and connection.
pstmt.close();
con.close();
/*************** End of Example Code ***************************************/
o While using JDBC you must handle several possible exceptions using try-catch blocks,
see Section 6.3.5 of your textbook.
o You can also examine the database metadata, please see Section 6.3.6 of the textbook.
3) SQLJ
SQLJ complements JDBC with a (semi-)static query model: Compiler can perform syntax
checks, strong type checks, consistency of the query with the schema. SQLJ is a part of the SQL
standard whereas embedded SQL is vendor-specific.
INTERNET APPLICATIONS
URI (Uniform Resource Identifier): Uniform naming schema to identify resources on the
Internet.
Example 1. http://www.cs.wisc.edu/~dbbook/index.html
URI has three parts:
 Naming schema (http)
 Name of the host computer (www.cs.wisc.edu)
 Name of the resource (~dbbook/index.html)
URLs are a subset of URIs
HTTP (HyperText Transfer Protocol)
 Client (web browser) sends HTTP request to server
 Server receives request and replies
 Client receives reply; makes new requests
Note that, HTTP is stateless:
 No “sessions”
 Every message is completely self-contained
 No previous interaction is “remembered” by the protocol
Web Data Formats
 HTML:

o The presentation language for the Internet.
o HTML is a markup language. Commands are tags
XML: A self-describing, hierarchal data model
o DTD: Standardizing schemas for Xml
XML – The Extensible Markup Language
 Language: A way of communicating information
 Markup: Notes or meta-data that describe your data or language
 Extensible: Limitless ability to define new languages or data sets
The point is that you can include your data and a description of what the data represents. This is
useful for defining your own language or protocol
Example 2. Chemical Markup Language
<molecule>
<weight>234.5</weight>
<Spectra>…</Spectra>
<Figures>…</Figures>
</molecule>
Components of Data-Intensive Systems
Three separate types of functionality:
 Data management
 Application logic
 Presentation
The system architecture determines whether these three components reside on a single system
(“tier) or are distributed across several tiers.
The Three Layers
 Presentation tier
o Primary interface to the user
o Needs to adapt to different display devices (PC, PDA, cell phone, voice access?)
 Middle tier
o Implements business logic (implements complex actions, maintains state between
different steps of a workflow)
o Accesses different data management systems
 Data management tier
o One or more standard database management systems
Example 3. A course enrollment system:
 Database System: Student info, course info, instructor info, course availability, pre-requisites,
etc.
 Application Server: Logic to add a course, drop a course, create a new course, etc.
 Client Program Log in different users (students, staff, faculty), display forms and humanreadable output
Presentation Tier



HTML Forms: How to pass data to the middle tier
JavaScript: Simple functionality at the presentation tier
Style sheets: Separating data from formatting
Presentation Tier Example: HTML Forms
 Common way to communicate data from client to middle tier. General format of a form:
<FORM ACTION=“page.jsp” METHOD=“GET” NAME=“LoginForm”>
…
</FORM>

Components of an HTML FORM tag:
ACTION: Specifies URI that handles the content
METHOD: Specifies HTTP GET or POST method
NAME: Name of the form; can be used in client-side scripts to refer to the form.

Inside HTML forms, there may be the INPUT tag. It has the following attributes:
o TYPE: text (text input field), password (text input field where input is, reset (resets all
input fields)
o NAME: symbolic name, used to identify field value at the middle tier.
o VALUE: default value
Example 4. A form that has two text input fields, one submit and one reset button.
<form method="POST" action="Welcome.jsp">
<input type="text" name="userid">
<input type="password" name="password">
<input type="submit" value="Login“ name="submit">
<input type=“reset” value=“Clear”>
</form>
Passing Arguments
o Two methods: GET and POST. Form contents go into the submitted URI. Structure:
action?name1=value1&name2=value2&name3=value3
o Action: name of the URI specified in the form. Note that the page named action needs to be a
program, script, or page that will process the user input
o (name,value)-pairs come from INPUT fields in the form; empty fields have empty values
(“name=“)
Example 5. Welcome.jsp?userid=john&password=johnpw
Presentation Tier: JavaScript
o Goal: Add functionality to the presentation tier. Sample applications:
o Detect browser type and load browser-specific page
o Form validation: Validate form input fields
o Browser control: Open new windows, close existing windows (example: pop-up ads)
o Usually embedded directly inside the HTML with the <SCRIPT>… </SCRIPT> tag.
Middle Tier
Middle tier encodes business logic, connects to database system(s), accepts form input from the
presentation tier, and generates output for the presentation tier. Technologies:
o
o
o
o
o
CGI: Protocol for passing arguments to programs running at the middle tier
Application servers: Runtime environment at the middle tier
Servlets: Java programs at the middle tier
JavaServerPages: Java scripts at the middle tier
PHP: PHP scripts at the middle tier.
Middle Tier Example: PHP
PHP is a widely-used general-purpose scripting language that is especially suited for Web
development and can be embedded into HTML.
Example 6
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php
echo '<p> Hello World</p>';
?>
</body>
</html>
Example 7. An example with database connection.
<html>
<head><title> EXAMPLE PAGE</title></head>
<body>
Hello World!!! This is my first PHP script as a CS352 student.... <br> <br>
Here is the list of all employees in our company database: <br> <br>
<?php
// Connect to server where your DB is, login and password to the DBMS (Here it is
// MySQL)
$connection = mysql_connect('139.179.21.74','company_user','123');
// Give an error if you can not connect
if(!connection)
die("Could not connect");
// Choose the database among those databases to use. As a company_user,
// we are allowed to use the company database.
mysql_select_db('company');
// Prepare a query string, just like we have done in Java
$query = "SELECT * FROM Employee";
// Send & execute the query, again this is similar to saying:
// "ResultSet rs =stmt.executeQuery($query)" in our java example
$result = mysql_query($query);
// This counts the number of tuples in the result
$result_no = mysql_num_rows($result);
// if some results are found, write them
if ($result_no >0)
{
for($i = 1; $i<=$result_no; $i++)
{
// This is used the fetch the contents of current record into the variables
// $employee_no, etc.
list($employee_no, $name…) = mysql_fetch_row($result);
// This is to write the output to HTML so that it is viewed by the browser
echo "NO: $employee_no NAME: $name SKILL: $skill …";
echo "<br>";
}
}
else
echo “no employee in the company database”
?>
</body>
</html>
Maintaining State
HTTP is stateless.
Advantages
o Easy to use: don’t need anything
o Great for static-information applications
o Requires no extra memory space
Disadvantages
o No record of previous requests means
o No shopping baskets or user logins
o No custom or dynamic content
o Security is more difficult to implement
How to maintain state?
Server-side state: Information is stored in a database, or in the application layer’s local memory
Client-side state: Information is stored on the client’s computer in the form of a cookie
Hidden state: Information is hidden within dynamically created web pages
The material discussed in this document is summarized from the slides of the textbook (Chapter
7) “Database Management Systems” by Ramakrishnan and Gehrke, 3rd Edition.