Real SQL Programming 1



Similar documents
Real SQL Programming. Embedded SQL Call-Level Interface Java Database Connectivity

SQL and Programming Languages. SQL in Programming Languages. Applications. Approaches

Real SQL Programming. Persistent Stored Modules (PSM) PL/SQL Embedded SQL

Jeffrey D. Ullman Anfang von: CS145 - Herbst Stanford University Online unter: Folien mit weißem Hintergrund wurden hinzugefügt!

CS346: Database Programming.

Chapter 13. Introduction to SQL Programming Techniques. Database Programming: Techniques and Issues. SQL Programming. Database applications

Programming Database lectures for mathema

Course Objectives. Database Applications. External applications. Course Objectives Interfacing. Mixing two worlds. Two approaches

SQL Programming. CS145 Lecture Notes #10. Motivation. Oracle PL/SQL. Basics. Example schema:

Internet Technologies

Short notes on webpage programming languages

PHP Tutorial From beginner to master

Introduction to Server-Side Programming. Charles Liu

HTML Forms and CONTROLS

Novell Identity Manager

Constraints, Triggers, and Database Programming Information Systems Q2, Ira Assent

Web Programming with PHP 5. The right tool for the right job.

TCP/IP Networking, Part 2: Web-Based Control

Java and Databases. COMP514 Distributed Information Systems. Java Database Connectivity. Standards and utilities. Java and Databases

HTML Tables. IT 3203 Introduction to Web Development

Forms, CGI Objectives. HTML forms. Form example. Form example...

Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved.

Database Programming. Week *Some of the slides in this lecture are created by Prof. Ian Horrocks from University of Oxford

HTML Form Widgets. Review: HTML Forms. Review: CGI Programs

SQL: Programming. Introduction to Databases CompSci 316 Fall 2014

SQL Injection for newbie

Chapter 9, More SQL: Assertions, Views, and Programming Techniques

CS412 Interactive Lab Creating a Simple Web Form

Designing for Dynamic Content

A table is a collection of related data entries and it consists of columns and rows.

Online Multimedia Winter semester 2015/16

PROJECT REPORT OF BUILDING COURSE MANAGEMENT SYSTEM BY DJANGO FRAMEWORK

PHP Authentication Schemes

07 Forms. 1 About Forms. 2 The FORM Tag. 1.1 Form Handlers

JavaScript Basics & HTML DOM. Sang Shin Java Technology Architect Sun Microsystems, Inc. sang.shin@sun.com

Further web design: HTML forms

Oracle Database: SQL and PL/SQL Fundamentals

CS 377 Database Systems SQL Programming. Li Xiong Department of Mathematics and Computer Science Emory University

Advanced Tornado TWENTYONE Advanced Tornado Accessing MySQL from Python LAB

NGASI AppServer Manager SaaS/ASP Hosting Automation for Cloud Computing Administrator and User Guide

FORM-ORIENTED DATA ENTRY

CTIS 256 Web Technologies II. Week # 1 Serkan GENÇ

database abstraction layer database abstraction layers in PHP Lukas Smith BackendMedia

SQL Injection Attack Lab Using Collabtive

JavaScript and Dreamweaver Examples

MyOra 3.0. User Guide. SQL Tool for Oracle. Jayam Systems, LLC

Working with forms in PHP

Oracle Database: SQL and PL/SQL Fundamentals NEW

XHTML Forms. Form syntax. Selection widgets. Submission method. Submission action. Radio buttons

Writing Scripts with PHP s PEAR DB Module

Talking to Databases: SQL for Designers

SQL Injection. SQL Injection. CSCI 4971 Secure Software Principles. Rensselaer Polytechnic Institute. Spring

Web Development. Owen Sacco. ICS2205/ICS2230 Web Intelligence

Database Programming with PL/SQL: Learning Objectives

Database Access via Programming Languages

Viewing Form Results

COSC 6397 Big Data Analytics. 2 nd homework assignment Pig and Hive. Edgar Gabriel Spring 2015

Java Application Developer Certificate Program Competencies

SQL is capable in manipulating relational data SQL is not good for many other tasks

Government Girls Polytechnic, Bilaspur

Database System Concepts

SQL Injection Attack Lab

INFORMATION BROCHURE Certificate Course in Web Design Using PHP/MySQL

Asset Management. By: Brian Johnson

AD-HOC QUERY BUILDER

Building a Customized Data Entry System with SAS/IntrNet

Example. Represent this as XML

<option> eggs </option> <option> cheese </option> </select> </p> </form>

c. Write a JavaScript statement to print out as an alert box the value of the third Radio button (whether or not selected) in the second form.

3M Information Technology

Advanced Web Technology 10) XSS, CSRF and SQL Injection 2

Oracle Database: SQL and PL/SQL Fundamentals

Java Server Pages and Java Beans

A Brief Introduction to MySQL

Data Transfer Tips and Techniques

Database Access from a Programming Language: Database Access from a Programming Language

Database Access from a Programming Language:

CGI Programming. What is CGI?

LogLogic General Database Collector for Microsoft SQL Server Log Configuration Guide

Perl/CGI. CS 299 Web Programming and Design

The Web Web page Links 16-3

Developing XML Solutions with JavaServer Pages Technology

HTML Forms. Pat Morin COMP 2405

2- Forms and JavaScript Course: Developing web- based applica<ons

Chapter 22 How to send and access other web sites

JavaScript: Arrays Pearson Education, Inc. All rights reserved.

Database 10g Edition: All possible 10g features, either bundled or available at additional cost.

Web Programming II JSP (Java Server Pages) ASP request processing. The Problem. The Problem. Enterprise Application Development using J2EE

Part II of The Pattern to Good ILE. with RPG IV. Scott Klement

What is a database? COSC 304 Introduction to Database Systems. Database Introduction. Example Problem. Databases in the Real-World

Database Applications Recitation 10. Project 3: CMUQFlix CMUQ s Movies Recommendation System

Web and e-business Technologies

Oracle For Beginners Page : 1

Now that we have discussed some PHP background

Inserting the Form Field In Dreamweaver 4, open a new or existing page. From the Insert menu choose Form.

It is highly recommended that you are familiar with HTML and JavaScript before attempting this tutorial.

MASTERTAG DEVELOPER GUIDE

Product: DQ Order Manager Release Notes

By Glenn Fleishman. WebSpy. Form and function

WEB DATABASE PUBLISHING

Transcription:

Real 1 We have seen only how SQL is used at the generic query interface an environment where we sit at a terminal and ask queries of a database. Reality is almost always different: conventional programs using SQL to interact with a database. 1 These slides have been adapted from those used by Jeff Ullman.

Options There are 3 ways in which programs are combined with SQL: 1. Code in a specialized language is stored in the database itself (e.g., PSM, PL/SQL). 2. SQL statements are embedded in a host language (e.g., C, Java). 3. Connection tools are used to allow a conventional language to access a database (e.g., CLI, JDBC, /PDO).

The first method is often called stored procedures : PSM, or persistent stored modules, allows us to store procedures as database schema elements. PSM = a mixture of conventional statements (if, while, etc.) and SQL. Lets us do things we cannot do in SQL alone. We can CREATE PROCEDUREs, e.g., and then CALL them from within SQL queries.

The second method uses embedded SQL: Key idea: A preprocessor turns SQL statements into procedure calls that fit with the surrounding host-language code. All embedded SQL statements begin with EXEC SQL, so the preprocessor can find them easily.

Shared Variables To connect SQL and the host-language program, the two parts must share some variables. Declarations of shared variables are bracketed by: EXEC SQL BEGIN DECLARE SECTION; <host-language declarations> EXEC SQL END DECLARE SECTION;

Use of Shared Variables In SQL, the shared variables must be preceded by a colon. They may be used as constants provided by the host-language program. They may get values from SQL statements and pass those values to the host-language program. In the host language, shared variables behave like any other variable.

Example: Looking Up Prices We will use C with embedded SQL to sketch the important parts of a function that obtains a beer and a bar, and looks up the price of that beer at that bar. Assumes the database contains the Sells(bar, beer, price) relation.

Example: C Plus SQL EXEC SQL BEGIN DECLARE SECTION; char thebar[21], thebeer[21]; float theprice; EXEC SQL END DECLARE SECTION; /* obtain values for thebar and thebeer */ EXEC SQL SELECT price INTO :theprice FROM Sells WHERE bar = :thebar AND beer = :thebeer; /* do something with theprice */

Need for Dynamic SQL Most applications use specific queries and modification statements to interact with the database. The preprocessor compiles EXEC SQL... statements into specific procedure calls and produces an ordinary host-language program that uses a library. What about situations in which query statements themselves are assembled by the host language, perhaps using user input? This gives rise to dynamic SQL.

Dynamic SQL Usually consists of two steps (SQL statements): 1. Preparing a query: EXEC SQL PREPARE <query-name> FROM <text of the query>; 2. Executing a query: EXEC SQL EXECUTE <query-name>; Prepare = optimize query. Prepare once, execute many times. If we are only going to execute the query once, we can combine the PREPARE and EXECUTE steps into one, using: EXEC SQL EXECUTE IMMEDIATE <text>;

Host/SQL Interfaces Via Libraries The third approach to connecting databases to conventional languages is to use library calls. C + CLI Java + JDBC + PDO We will only consider + PDO.

Three-Tier Architecture for Web Access A common environment for using a database over the Web has three tiers of processors: 1. Web servers talk to the user. 2. Application servers execute the business logic. 3. servers get what the application servers need from the database.

Example: Amazon holds the information about products, customers, etc. Business logic includes things like what do I do after someone clicks checkout? Answer: Show the how will you pay for this? screen.

SQL/CLI Instead of using a preprocessor (as in embedded SQL), we can use a library of functions. The library for C is called SQL/CLI = Call-Level Interface. s preprocessor will translate the EXEC SQL... statements into CLI or similar calls, anyway.

: Hypertext Preprocessor () is an open-source, server-side scripting language It is interpreted, so no possibility of using EXEC SQL and a preprocessor. Can be embedded within HTML on a web page in order to generate dynamic content. uses <?php and?> delimiters for code. delimiters differentiate the code from static HTML. DB library is called PDO ( Data Objects). Variables (which must start with $) don t have to be declared and are not strongly typed. web server needs to have installed.

Making a Connection Example: <?php $dbhost = mysql:host=mysqlsrv.dcs.bbk.ac.uk; dbname=... ; $dbuser =... ; $dbpass =... ; $db = new PDO($dbhost, $dbuser, $dbpass);...?> We want to connect to a mysql server, and need to give the name of the machine it runs on. We need to specify the database name (dbname). The user name and password are also required. PDO object allows us to open a connection to the database specified by the values of the variables.

Executing an SQL Statement Example: <?php... $db = new PDO($dbhost, $dbuser, $dbpass); $result = $db->query( "select count(*) from Drinkers");...?> The query method applies to a connection object. It takes a string argument and returns a result. Could be an error code or the relation returned by the query.

Retrieving a Query Result Example: $count = $result->fetchcolumn(0); print ("There are $count rows in Drinkers."); The result of a query is the set of rows returned. In our example, only one row is returned, with one column (the count). Method fetchcolumn applies to the result, and fetchcolumn(0) returns the value of the first column. This can then be output using the print function. This output is returned by the web server to the browser which requested the page.

String Values solves a problem for languages that commonly construct strings as values: How do I tell whether a substring needs to be interpreted as a variable and replaced by its value? solution: Double quotes means replace; single quotes means don t. Example: $100 = "one hundred dollars"; $sue = You owe me $100. ; $joe = "You owe me $100."; Value of $sue is You owe me $100. Value of $joe is You owe me one hundred dollars.

Complete Example <html> <body> <h2>counting the number of drinkers</h2> <p> <?php $dbhost = mysql:host=mysqlsrv.dcs.bbk.ac.uk;dbname=.. $dbuser =... ; $dbpass =... ; $db = new PDO($dbhost, $dbuser, $dbpass); $result = $db->query("select count(*) from Drinkers"); $count = $result->fetchcolumn(0); print ("There are $count rows in Drinkers.");?> </p> </body> </html>

Example Explained Notice that the code is embedded in HTML. Whatever is output by the script (using print will be embedded in the HTML in place of the script source code. The file is accessible as http://www.dcs.bbk. ac.uk/~ptw/teaching/dbm/php/db1.php. Creating a link to this URL, or entering it as an address into a browser will result in the DCS web server executing the code.

Processing a Set of Rows (1) Say the query in our program is: $result = $db->query( "select * from Drinkers"); This returns a number of rows, so we use a while loop. We want to output the rows as an HTML table. So we need to output HTML table tags <table> and </table> before and after the script. Each time around the while loop, we output HTML row tags <tr> and </tr>. We also need an inner (for) loop to output each column value, inside HTML <td> and </td> tags.

Processing a Set of Rows (2) while ($row = $result->fetch()) { print ("<tr>"); for ($i = 0; $i < $result->columncount(); $i++) { print ("<td> $row[$i] </td>"); } print ("</tr>"); } fetch() method fetches the next row as an array. columncount() returns the number of columns. $row[$i] is the value of the i th column of the current row. The file is accessible as http://www.dcs.bbk. ac.uk/~ptw/teaching/dbm/php/db2.php.

Processing a Set of Rows (3) The HTML generated by the script is as follows: <html> <body> <h1>the Drinkers Table</h1> <table border= 2 > <tr><td> Alice </td><td> Islington </td></tr> <tr><td> Bob </td><td> Bloomsbury </td></tr> <tr><td> Carol </td><td> Islington </td></tr> <tr><td> Dave </td><td> Bloomsbury </td></tr> <tr><td> Eve </td><td> Stratford </td></tr> </table> </body> </html>

Arrays Two kinds: numeric and associative. Numeric arrays are ordinary, indexed 0, 1,... Example: $a = array("paul", "George", "John", "Ringo"); Then $a[0] is "Paul", $a[1] is "George", and so on.

Associative Arrays Elements of an associative array $a are pairs x => y, where x is a key string and y is any value. If x => y is an element of $a, then $a[x] is y. uses associative arrays for retrieving the data that users enter into HTML forms.

Retrieving User Input Let s say we want to allow users to enter the name of the database table whose contents they wish to be displayed. We can use an HTML form, with a field (text box) where they can enter the table name. The value they enter must be sent to the web server along with the request to run a script. The script must be able to retrieve this value and use it as part of an SQL query.

An HTML Form The HTML form is available at http://www.dcs.bbk. ac.uk/~ptw/teaching/dbm/php/db.html and the source code used on it is explained on the following slides.

HTML Form Explained <form action="db3.php" method="get"> Table: <input type="text" name="tablename" /> <input type="submit" /> </form> The form element has an action attribute which specifies the URL of the script (...db3.php) to be run. The form element has a method attribute which specifies that the HTTP GET method is to be used. This will send the user s input appended to the URL of the script and separated by a? (a so-called query string ). The form has two input elements, one representing a text box; the other a submit button. The name of the text box is tablename.

Processing User Input... $table = $_GET[ tablename ]; print ("<h1>the $table Table</h1>"); $query = "select * from $table"; $result = $db->query($query);... The rest of the script is as before. $_GET is a built-in associative array, indexed by the names of the text boxes used on the form. Each value is whatever the user typed into the corresponding text box. If the user typed Pubs (without the quotes) into the text box named tablename on the form, then $_GET[ tablename ] will be replaced by Pubs (without the quotes).

Using Prepared Statements The query method executes an SQL statement immediately. PDO can also prepare and execute statements separately. Prepared statements have some advantages: Statement strings can contain placeholders rather than literal data values (see next slide). A prepared statement can be executed repeatedly without the need for the DBMS to work out an execution plan each time.

Placeholders in SQL Statements Where users are expected to provide values for SQL statements at run-time, placeholders can be used. Anonymous placeholders are indicated by? characters in the SQL query string. The program then associates values with these by providing an array of values. Named placeholders are indicated by a name preceded by a colon, e.g., :location. Values are associated with named placeholders by using either an associative array or the bindparam method.

Anonymous Placeholders $query = "select price from Sells where pub=? and beer=?"; $stmt = $db->prepare($query); $pub = $_GET[ pub ]; $beer = $_GET[ beer ]; $stmt->execute(array($pub, $beer)); $row = $stmt->fetch(); print ("<h2>the $pub sells $beer for $row[0]</h2>"); Query finds the price of a given beer sold by a given pub ( script db4.php). The text boxes in the form are named pub and beer. The value of $_GET[ pub ] is associated with the first? in the query, while the value of $_GET[ beer ] is associated with the second?.

Named Placeholders (1) $query = "insert into Pubs (name, location) values (:name, :location)"; $stmt = $db->prepare($query); $pub = $_GET[ pub ]; $location = $_GET[ location ]; $stmt->bindparam( :name, $pub); $stmt->bindparam( :location, $location);... SQL statement inserts a pub name and location into Pubs ( script db5.php). The text boxes in the form are named pub and location. The placeholders are :name and :location. bindparam binds each placeholder (parameter) to a value (from the form).

Named Placeholders (2)... if ($stmt->execute()) print ("<h2>the $pub in $location inserted</h2>"); else { print ("<h2>failed to insert the $pub in $location</h2>"); print_r($stmt->errorinfo()); } execute returns a Boolean, indicating success or failure. errinfo() returns an array of error information. print_r displays information about a variable in readable form.