Server-Side Application and Data Management IT IS 3105 (Spring 2010)

Slides:



Advertisements
Similar presentations
1 Lecture 02: SQL. 2 Outline Data in SQL Simple Queries in SQL (6.1) Queries with more than one relation (6.2) Recomeded reading: Chapter 3, Simple Queries.
Advertisements

SQL Introduction Standard language for querying and manipulating data Structured Query Language Many standards out there: SQL92, SQL2, SQL3. Vendors support.
Introduction to Structured Query Language (SQL)
Introduction to Structured Query Language (SQL)
Matthew P. Johnson, OCL1, CISDD CUNY, F20041 OCL1 Oracle 8i: SQL & PL/SQL Session #3 Matthew P. Johnson CISDD, CUNY Fall, 2004.
1 Lecture 02: Basic SQL. 2 Outline Data in SQL Simple Queries in SQL Queries with more than one relation Reading: Chapter 3, “Simple Queries” from SQL.
Introduction to Structured Query Language (SQL)
1 Lecture 2: SQL Wednesday, January 7, Agenda Leftovers from Monday The relational model (very quick) SQL Homework #1 given out later this week.
1 Information Systems Chapter 6 Database Queries.
Your Oracle Account UserName is the same as your UWP username Followed Not case sensitive Initial Password: UWPstudent Password is case sensitive.
1. Midterm summary Types of data on the web: unstructured, semi- structured, structured Scale and uncertainty are key features Main goals are to model,
PHP Programming with MySQL Slide 8-1 CHAPTER 8 Working with Databases and MySQL.
Intro. to SQL DSC340 Mike Pangburn. Learning Objectives Understand the data-representation terminology underlying relational databases Understand core.
Chapter 7 Working with Databases and MySQL PHP Programming with MySQL 2 nd Edition.
CPS120: Introduction to Computer Science Lecture 19 Introduction to SQL.
Structured Query Language Chris Nelson CS 157B Spring 2008.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
Database Management COP4540, SCS, FIU Structured Query Language (Chapter 8)
SQL. SQL Introduction Standard language for querying and manipulating data Structured Query Language Many standards out there: ANSI SQL, SQL92 (a.k.a.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
Chapter 8 Manipulating MySQL Databases with PHP PHP Programming with MySQL 2 nd Edition.
1 Introduction to Database Systems CSE 444 Lecture 02: SQL September 28, 2007.
1 Lecture 02: SQL Friday, September 30, Administrivia Homework 1 is out. Due: Wed., Oct. 12 Did you login on IISQLSRV ? Did you change your password.
Lectures 2&3: Introduction to SQL. Lecture 2: SQL Part I Lecture 2.
Hassan Tariq INTRODUCTION TO SQL What is SQL? –When a user wants to get some information from a database file, he can issue a query. – A query is a user–request.
Chapter 3: Relational Databases
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
SQL. SQL Introduction Standard language for querying and manipulating data Structured Query Language Many standards out there: ANSI SQL, SQL92 (a.k.a.
Fundamentals of DBMS Notes-1.
Web Systems & Technologies
SQL.
Chapter 5 Introduction to SQL.
 2012 Pearson Education, Inc. All rights reserved.
Server-Side Application and Data Management IT IS 3105 (FALL 2009)
Server-Side Application and Data Management IT IS 3105 (FALL 2009)
Server-Side Application and Data Management IT IS 3105 (FALL 2009)
CS1222 Using Relational Databases and SQL
ORACLE SQL Developer & SQLPLUS Statements
Lecture 2 (cont’d) & Lecture 3: Advanced SQL – Part I
ISC440: Web Programming 2 Server-side Scripting PHP 3
Structured Query Language
Chapter 8 Working with Databases and MySQL
March 30th – intro to joins
Cse 344 January 10th –joins.
CS4222 Principles of Database System
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
Introduction to SQL Wenhao Zhang October 5, 2018.
CSE544 SQL Wednesday, March 31, 2004.
CMPT 354: Database System I
SQL-1 Week 8-9.
Lectures 3: Introduction to SQL 2
Introduction to Database Systems CSE 444 Lecture 02: SQL
Session - 6 Sequence - 1 SQL: The Structured Query Language:
Contents Preface I Introduction Lesson Objectives I-2
CS1222 Using Relational Databases and SQL
CS1222 Using Relational Databases and SQL
Sampath Jayarathna Cal Poly Pomona
Lectures 2: Introduction to SQL 1
Instructor: SAMIA ARSHAD
CS1222 Using Relational Databases and SQL
Introduction to SQL Server and the Structure Query Language
CS1222 Using Relational Databases and SQL
Presentation transcript:

Server-Side Application and Data Management IT IS 3105 (Spring 2010) Lecture x

http://www.learn-sql- tutorial.com/DatabaseBasics.cfm

Introduction to Relational Databases

Database Overview A database provides a means to organize and retrieve data. The database is the set of physical files in which all the objects and database metadata are stored. These files can usually be seen at the operating system level.

Database overview Different types of Database structures (Hierarchical, Relational, Temporal) are based on the way they store the data on Hard Disk Drive and how they read from the stored data. Famous Relational Databases: Oracle, MS SQL (Microsoft), DB2 (IBM), MySQL, mSQL, Postgre SQL and etc. MySQL is an open source relational database management system (RDBMS) that uses Structured Query Language (SQL), the most popular language for adding, accessing, and processing data in a database.

Database Introduction RDBMS (Relational Database Management System) RDBMSs can provide faster access to data than flat files. RDBMSs can be easily queried (SQL Language) to extract sets of data that fit certain criteria. RDBMSs have built-in mechanisms for dealing with concurrent access so that you as a programmer don't have to worry about it. RDBMSs have built-in privilege systems.

SQL SQL: “Structured Query Language”—the most common standardized language used to access databases. SQL has several parts: DDL – Data Definition Language {Defining, Deleting, Modifying relation schemas} DML – Data Manipulation Language {Inserting, Deleting, Modifying tuples in database} Embedded SQL – defines how SQL statements can be used with general-purposed programming

Basic Definitions Table, a set of columns that contain data. In the old days, a table was called a file. Row, a set of columns from a table reflecting a record. Index, an object that allows for fast retrieval of table rows. Every primary key and foreign key should have an index for retrieval speed. Primary key, often designated pk, is 1 or more columns in a table that uniquely identify a record.

Basic Definitions Relational databases are made up of relations, more commonly called tables. A table is exactly what it sounds like a table of data. If you've used an electronic spreadsheet (Excel), you've already used a relational table. A database usually consists of several tables. MySQL can handle thousands of databases. Table Database

Basic Definitions number name department salary location Kerwin 413 2000 New Jersey 34589 Larson 642 1800 Los Angeles 35761 Myers 611 1400 Orlando 47132 Neumann 9000 78321 Stephens 8500 Row Column Primary key number name department salary location 23603 Jones 413 1100 New Jersey 24568

Basic Definitions Elements of the relational database table: Table Key (auto-increase) Attribute Column Row (Topple) Foreign Key (referring to another table) Cell

Basic Definitions Foreign key, often designated fk, is a common column common between 2 tables that define the relationship between those 2 tables. Foreign keys are either mandatory or optional. Mandatory forces a child to have a parent by creating a not null column at the child. Optional allows a child to exist without a parent, allowing a nullable column at the child table (not a common circumstance).

Foreign Key (referring to another table) Basic Definitions Foreign Key (1 to Many): Foreign Key (referring to another table) Table: Patient_information (MANY) Table: City_information (ONE)

Basic Definitions Foreign Key (Many to Many): Patient #1 has doctor #4, #5 and #6. Dr. #1 has patient #2 and #4. Table: Doctor_information (MANY) Table: Patient_information (MANY) Table: Patient_Doctor_realationship

Create a Database An SQL relation is defined using the CREATE DATABASE command: create database [database name] Showing what are the available databases, use the show command: show databases; Using a specific database: use [database name]

Create Table An SQL relation is defined using the CREATE TABLE command: Create table [tablename] (A1 T1,A2 T2, … An Tn, (integrity-constraint1), …, (integrity-constraintk)) Each Ai is an attribute name in the table Each Ti is the data type of values for Ai Example Create table student (SID char(9) not null, name varchar(30), age integer, department varchar(20), primary key (SID) );

Insert into a Table Add a new tuple to a table: insert into table name values(V1, V2, V2);

Create Table An SQL relation is defined using the CREATE TABLE command: Create table [tablename] (A1 T1,A2 T2, … An Tn, (integrity-constraint1), …, (integrity-constraintk)) Each Ai is an attribute name in the table Each Ti is the data type of values for Ai Example Create table students (SID char(9) not null, name varchar(30), age integer, dept varchar(20), primary key (SID) );

Drop and Alter Table The DROP TABLE command deletes all information about the dropped relation from the database The ALTER TABLE command is used to add attributes to or remove attributes from an existing relation (table): alter table tablename actions where actions can be one of following actions: ADD Attribute DROP Attribute ADD PRIMARY KEY (Attribute_name1,…) DROP PRIMARY KEY

Insert into a Table Add a new tuple to a table: Example: insert into table name values(V1, V2, V3); insert into table name (C1, C2, C3) values(V1, V2, V3); Example: insert into students values (800123456, ‘Bob’, 25, SIS); insert into students (SID, name, age, dept) values (800123456, ‘Bob’, 25, SIS); Inserting multiple tuples: insert into table name (C1, C2, C3) values(V1, V2, V3), (V1, V2, V3), (V1, V2, V3); Example insert into students (SID, name, age, dept) values (800123456, ‘Bob’, 25, SIS), (800678912, ‘Alice’, 20, CS);

Writing Database Queries A typical SQL query has the form: select A1, A2, …, An from table1, table2, …, tablem where P Ai represents an attribute tablei represents a table P is a constraints (condition) Example select SID, name from student where dept=‘SIS’;

SQL Query Basic form: SELECT attributes FROM relations (possibly multiple, joined) WHERE conditions (selections)

Simple SQL Query SELECT * FROM Product WHERE category=‘Gadgets’ PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi SELECT * FROM Product WHERE category=‘Gadgets’ PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 “selection”

Simple SQL Query Product PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi SELECT PName, Price, Manufacturer FROM Product WHERE Price > 100 PName Price Manufacturer SingleTouch $149.99 Canon MultiTouch $203.99 Hitachi “selection” and “projection”

A Notation for SQL Queries Input Schema Product(PName, Price, Category, Manfacturer) SELECT Name, Price, Manufacturer FROM Product WHERE Price > 100 Answer(PName, Price, Manfacturer) Output Schema

Selections What goes in the WHERE clause: x = y, x < y, x <= y, etc For number, they have the usual meanings For CHAR and VARCHAR: lexicographic ordering Expected conversion between CHAR and VARCHAR For dates and times, what you expect... Pattern matching on strings: s LIKE p (next)

The LIKE operator s LIKE p: pattern matching on strings p may contain two special symbols: % = any sequence of characters _ = any single character Product(Name, Price, Category, Manufacturer) Find all products whose name mentions ‘gizmo’: SELECT * FROM Products WHERE PName LIKE ‘%gizmo%’

Eliminating Duplicates Category Gadgets Photography Household SELECT DISTINCT category FROM Product Compare to: Category Gadgets Photography Household SELECT category FROM Product

Ordering the Results SELECT pname, price, manufacturer FROM Product WHERE category=‘gizmo’ AND price > 50 ORDER BY price, pname Ordering is ascending, unless you specify the DESC keyword. Ties are broken by the second attribute on the ORDER BY list, etc.

Joins in SQL Connect two or more tables: What is the Connection PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Product Company CName StockPrice Country GizmoWorks 25 USA Canon 65 Japan Hitachi 15 What is the Connection between them ?

Join between Product and Company Joins Product (pname, price, category, manufacturer) Company (cname, stockPrice, country) Find all products under $200 manufactured in Japan; return their names and prices. Join between Product and Company SELECT PName, Price FROM Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200

Joins in SQL Product Company PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Cname StockPrice Country GizmoWorks 25 USA Canon 65 Japan Hitachi 15 SELECT PName, Price FROM Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200 PName Price SingleTouch $149.99

Joins Product (pname, price, category, manufacturer) Purchase (buyer, seller, store, product) Person(persname, phoneNumber, city) Find names of people living in Seattle that bought some product in the ‘Gadgets’ category, and the names of the stores they bought such product from SELECT DISTINCT persname, store FROM Person, Purchase, Product WHERE persname=buyer AND product = pname AND city=‘Seattle’ AND category=‘Gadgets’

Disambiguating Attributes Sometimes two relations have the same attr: Person(pname, address, worksfor) Company(cname, address) Which address ? SELECT DISTINCT pname, address FROM Person, Company WHERE worksfor = cname SELECT DISTINCT Person.pname, Company.address FROM Person, Company WHERE Person.worksfor = Company.cname

Tuple Variables Product (pname, price, category, manufacturer) Purchase (buyer, seller, store, product) Person(persname, phoneNumber, city) Find all stores that sold at least one product that the store ‘BestBuy’ also sold: SELECT DISTINCT x.store FROM Purchase AS x, Purchase AS y WHERE x.product = y.product AND y.store = ‘BestBuy’ Answer (store)

Aliases for Columns and Tables SELECT col1 alias1, col2 alias2 from tablename; Example: SELECT SID id, name nm, age, dept dno from students; SELECT col1, col2 from tablename AS alias1; SELECT SID, name from students as t1;

Aggregate Functions Aggregate functions operate on the multiset of values of a attribute and return a value avg(attribute): average value min(attribute): minimum value max(attribute): maximum value sum(attribute): sum of values count(attribute): number of values To obtain the value when duplicates are removed, insert the keyword distinct before attribute name: avg(distinct attribute)

Aggregate Functions A complete list is available at: http://dev.mysql.com/doc/refman/5.0/en/func- op-summary-ref.html

Modifying the Database Three cases: Add a tuple INSERT INTO table_name VALUES (Val1, Val2, … , Valn) Change tuples UPDATE table_name SET A1=val1, A2=val2, …, An=valn WHERE tuple_selection_predicate Remove tuples DELETE FROM table_name

UPDATE Set all department to ‘computer science’ update student set dept=‘computer science’ In table student(SID, name, age, dept), increase the age of everyone by 1. update student set age=age+1 In table student, update the department for the user with SID ‘800123456’ to ‘CS’ Update student set dept=‘CS’ where SID=800123456

DELETION Delete records of all students in the university delete from student Delete the students who study computer science where dept=‘CS’

Setting up the Connection The PHP library for connecting to MySQL is called mysqli, where the i stands for improved. To connect to the MySQL server: $hostname = “localhost”; $username = “root”; $password = “123456”; $dbname = “mydb”; $db = new mysqli($hostname, $username, $password, $dbname); This line instantiate the mysqli class and creates a connection to the localhost and database with the specified username, and password.

Setting up the Connection The result of your attempt to connect is checked using the $db->connect_error value: $db = new mysqli($hostname, $username, $password, $dbname); if($db->connect_error){ echo ‘Error:’ . $db->connect_error; exit; }

Querying the Database Prepare a query string, then call the mysqli query method: $query = “select * from students”; $result = $db->query($query); In case of SELECT the query method returns a result set and false if there is an error. The result set can be accessed in multiple ways.

Querying the Database Accessing the result set: Method Description $result->fetch_assoc() Returns an associative array of strings representing the fetched row in the result set, where each key in the array represents the name of one of the result set's columns or NULL if there are no more rows in resultset. $result->fetch_row() Fetches one row of data from the result set and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero). $result->fetch_object() Returns the current row result set as an object where the attributes of the object represent the names of the fields found within the result set.

$result->fetch_assoc() while($row = $result->fetch_assoc()){ echo $row[“SID”] . “, “; echo $row[“fname”] . “, “; echo $row[“lname”] . “, “; echo $row[“age”] . “<br>“; }

$result->fetch_row() while($row = $result->fetch_row()){ echo $row[0] . “, “; echo $row[1] . “, “; echo $row[2] . “, “; echo $row[3] . “<br>“; }

$result->fetch_object() while($row = $result->fetch_object()){ echo $row->SID . “, “; echo $row->fname . “, “; echo $row->lname . “, “; echo $row->age. “<br>“; }

Important result set attributes and methods Attribute/Method Description $result->num_rows Returns the number of rows in the result set. $result->field_count Returns the number of fields from specified result set. $result->data_seek ( int $offset ) Seeks to an arbitrary result pointer specified by the offset in the result set. The offset must be between (0 to result->num_rows -1) $result->free() Frees the memory associated with a result

Inserting into the Database Prepare a query string, then call the mysqli query method: $query = “insert into students (SID, fname, lname, age, dept) values (‘800456783’,‘Bob’,’Smith’,25,’SIS’)”; $result = $db->query($query); In case of INSERT the query method returns true if the insert is successful and false if there is an error.

Inserting into the Database Checking the result status after an insert: if ($result) { echo $db->affected_rows." students inserted into database."; } else { echo "An error has occurred. The item was not added."; }

Other Database Object Methods and Attributes $db->affected_rows Returns the number of rows affected by the last INSERT, UPDATE, REPLACE or DELETE query. For SELECT statements returns the number of returned rows. $db->close() Closes a previously opened database connection For a detailed description of mysqli class check: http://us2.php.net/manual/en/mysqli.summary.php

Using Prepared Statements Mysqli library supports the use of prepared statements. Prepared statements are useful for speeding up execution when you are performing large numbers of the same query with different data. They also protect against SQL injection-style attacks.

Using Prepared Statements $query = "insert into students (SID, fname, lname, age, dept) values(?, ?, ?, ?, ?)"; $stmt = $db->prepare($query); $stmt->bind_param("sssds", $sid, $fname, $lname, $age, $dept); $sid = “800999234”; $fname=“Bob”; $lname=“Smith”; $age=23; $dept=“SIS”; $stmt->execute(); echo $stmt->affected_rows.' students inserted into database.'; $stmt->close(); Char Description i Variable has type integer d Variable has type double s Variable has type string b Variable has type blob

MySQL (Creating Tables) CREATE TABLE tbl_name (att1 type, att2 type,…,attn type, conditions) CREATE TABLE users ( uid VARCHAR(20), password VARCHAR(20), dept VARCHAR(10), primary key (uid));

MySQL (Creating Tables) What if you want to create the table only if it does not exist? CREATE TABLE IF NOT EXISTS tbl_name (att1 type, att2 type,…,attn type, conditions

MySQL (Inserting) INSERT INTO tbl_name (col1, …, coln) values (val1, .. val2) INSERT INTO users (uid, password, dept) values (‘bsmith’, ‘pass1’, ‘SIS’); Can I insert multiple values? INSERT INTO users (uid, password, dept) values (‘bsmith’, ‘pass1’, ‘SIS’),(‘ajames’, ‘pass2’, ‘CS’)

MySQL (Updating) How can I change values already stored ? To change values for specific tuples then you have to think about how will you identify these specific tuples? For example, how to change the department of ‘bsmith’ to ‘CS’? UPDATE users SET dept=‘CS’ WHERE uid=‘bsmith’ If you forget the WHERE Clause then all tuples in the table will be updates!

MySQL (Query) SELECT att1,att2,att3 FROM table1, table2, table3 WHERE conditions Find the password for user ‘bsmith’ SELECT password FROM users WHERE uid =‘bsmith’ Find if user ‘bsmith’ is a valid user SELECT count(*) as cnt FROM users WHERE uid = ‘bsmith’ This returns a column called cnt which contains the number of users which have the uid=‘bsmith’

MySQL (Query) Given a certain password how can I verify that this is the password for ‘bsmith’ SELECT count(*) cnt FROM users WHERE uid=‘bsmith’ AND password=‘provided password’ How to find all users that have usernames that start with ‘b’ ? SELECT uid FROM users WHERE uid LIKE ‘b%’

MySQL Date and Time Functions CURDATE() : returns the current date SELECT CURDATE(); DATE_FORMAT(date, format): formats the date value according to the format string For the format strings go to : http://dev.mysql.com/doc/refman/5.1/en/date-and-time- functions.html SELECT DATE_FORMAT(CURDATE(),’%W %M %Y’)

PHP (Intersting Variables) $_POST $_GET $_COOKIE $_SESSION

PHP (interesting functions) header(): most common use is to redirect the user’s browser to another url: header(‘Location: http://www.abc.com’); implode(): Joins array elements with a string and returns a string. implode(‘-’, $array) Terminating: exit(‘error message’) die(‘error message’)