Download presentation
Presentation is loading. Please wait.
Published byMelina Goodman Modified over 6 years ago
1
Server-Side Application and Data Management IT IS 3105 (Spring 2010)
Lecture x
3
http://www.learn-sql- tutorial.com/DatabaseBasics.cfm
4
Introduction to Relational Databases
5
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.
6
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.
7
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.
8
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
9
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.
10
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
11
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
12
Basic Definitions Elements of the relational database table: Table
Key (auto-increase) Attribute Column Row (Topple) Foreign Key (referring to another table) Cell
13
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).
14
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)
15
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
16
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]
17
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) );
18
Insert into a Table Add a new tuple to a table:
insert into table name values(V1, V2, V2);
19
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) );
20
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
21
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 ( , ‘Bob’, 25, SIS); insert into students (SID, name, age, dept) values ( , ‘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 ( , ‘Bob’, 25, SIS), ( , ‘Alice’, 20, CS);
22
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’;
23
SQL Query Basic form: SELECT attributes
FROM relations (possibly multiple, joined) WHERE conditions (selections)
24
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”
25
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”
26
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
27
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)
28
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%’
29
Eliminating Duplicates
Category Gadgets Photography Household SELECT DISTINCT category FROM Product Compare to: Category Gadgets Photography Household SELECT category FROM Product
30
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.
31
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 ?
32
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
33
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
34
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’
35
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
36
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)
37
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;
38
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)
39
Aggregate Functions A complete list is available at:
op-summary-ref.html
40
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
41
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 ‘ ’ to ‘CS’ Update student set dept=‘CS’ where SID=
42
DELETION Delete records of all students in the university
delete from student Delete the students who study computer science where dept=‘CS’
43
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.
44
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; }
45
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.
46
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.
47
$result->fetch_assoc()
while($row = $result->fetch_assoc()){ echo $row[“SID”] . “, “; echo $row[“fname”] . “, “; echo $row[“lname”] . “, “; echo $row[“age”] . “<br>“; }
48
$result->fetch_row()
while($row = $result->fetch_row()){ echo $row[0] . “, “; echo $row[1] . “, “; echo $row[2] . “, “; echo $row[3] . “<br>“; }
49
$result->fetch_object()
while($row = $result->fetch_object()){ echo $row->SID . “, “; echo $row->fname . “, “; echo $row->lname . “, “; echo $row->age. “<br>“; }
50
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
51
Inserting into the Database
Prepare a query string, then call the mysqli query method: $query = “insert into students (SID, fname, lname, age, dept) values (‘ ’,‘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.
52
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."; }
53
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:
54
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.
55
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 = “ ”; $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
56
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));
57
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
58
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’)
59
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!
60
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’
61
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%’
62
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 : functions.html SELECT DATE_FORMAT(CURDATE(),’%W %M %Y’)
63
PHP (Intersting Variables)
$_POST $_GET $_COOKIE $_SESSION
64
PHP (interesting functions)
header(): most common use is to redirect the user’s browser to another url: header(‘Location: implode(): Joins array elements with a string and returns a string. implode(‘-’, $array) Terminating: exit(‘error message’) die(‘error message’)
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.