Real SQL Programming 1

Size: px
Start display at page:

Download "Real SQL Programming 1"

Transcription

1 Real SQL Programming 1

2 SQL in Real Programs 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 interacting with SQL 2

3 Options 1. Code in a specialized language is stored in the database itself (e.g., PSM, PL/pgsql) 2. SQL statements are embedded in a host language (e.g., C) 3. Connection tools are used to allow a conventional language to access a database (e.g., CLI, JDBC, PHP/DB) 3

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

5 Procedures in PostgreSQL CREATE PROCEDURE <name> ([<arguments>]) AS $$ <program>$$ LANGUAGE <lang>; PostgreSQL only supports functions: CREATE FUNCTION <name> ([<arguments>]) RETURNS VOID AS $$ <program>$$ LANGUAGE <lang>; 5

6 Parameters for Procedures Unlike the usual name-type pairs in languages like Java, procedures use modename-type triples, where the mode can be: IN = function uses value, does not change OUT = function changes, does not use INOUT = both 6

7 Example: Stored Procedure Let s write a procedure that takes two arguments b and p, and adds a tuple to Sells(bar, beer, price) that has bar = C.Ch., beer = b, and price = p Used by Cafe Chino to add to their menu more easily 7

8 The Procedure CREATE FUNCTION ChinoMenu ( IN b CHAR(20), IN p REAL ) RETURNS VOID AS $$ INSERT INTO Sells VALUES( C.Ch., b, p); $$ LANGUAGE plpgsql; Parameters are both read-only, not changed The body --- a single insertion 8

9 Invoking Procedures Use SQL/PSM statement CALL, with the name of the desired procedure and arguments Example: CALL ChinoMenu( Eventyr, 50); Functions used in SQL expressions wherever a value of their return type is appropriate No CALL in PostgreSQL: SELECT ChinoMenu( Eventyr, 50); 9

10 Kinds of PL/pgsql statements Return statement: RETURN <expression> returns value of a function Like in Java, RETURN terminates the function execution Declare block: DECLARE <name> <type> used to declare local variables Groups of Statements: BEGIN... END Separate statements by semicolons 10

11 Kinds of PL/pgsql statements Assignment statements: <variable> := <expression>; Example: b := Od.Cl. ; Statement labels: give a statement a label by prefixing a name and a colon 11

12 IF Statements Simplest form: IF <condition> THEN <statements(s)> END IF; Add ELSE <statement(s)> if desired, as IF... THEN... ELSE... END IF; Add additional cases by ELSEIF <statements(s)>: IF THEN ELSEIF THEN ELSEIF THEN ELSE END IF; 12

13 Example: IF Let s rate bars by how many customers they have, based on Frequents(drinker,bar) <100 customers: unpopular customers: average >= 200 customers: popular Function Rate(b) rates bar b 13

14 Example: IF CREATE FUNCTION Rate (IN b CHAR(20)) RETURNS CHAR(10) AS $$ DECLARE cust INTEGER; Number of customers of bar b BEGIN cust := (SELECT COUNT(*) FROM Frequents WHERE bar = b); IF cust < 100 THEN RETURN unpopular ; ELSEIF cust < 200 THEN RETURN average ; ELSE RETURN popular ; END IF; END; Nested IF statement 14

15 Loops Basic form: <<<label>>> LOOP <statements> END LOOP; Exit from a loop by: EXIT <label> WHEN <condition> 15

16 Example: Exiting a Loop <<loop1>> LOOP... EXIT loop1 WHEN...;... END LOOP;... control winds up here If this statement is executed and the condition holds... 16

17 Other Loop Forms WHILE <condition> LOOP <statements> END LOOP; Equivalent to the following LOOP: LOOP EXIT WHEN NOT <condition>; <statements> END LOOP; 17

18 Other Loop Forms FOR <name> IN <start> TO <end> LOOP <statements> END LOOP; Equivalent to the following block: <name> := <start>; LOOP EXIT WHEN <name> > <end>; <statements> <name> := <name>+1; END LOOP; 18

19 Other Loop Forms FOR <name> IN REVERSE <start> TO <end> LOOP <statements> END LOOP; Equivalent to the following block: <name> := <start>; LOOP EXIT WHEN <name> < <end>; <statements> <name> := <name> - 1; END LOOP; 19

20 Other Loop Forms FOR <name> IN <start> TO <end> BY <step> LOOP <statements> END LOOP; Equivalent to the following block: <name> := <start>; LOOP EXIT WHEN <name> > <end>; <statements> <name> := <name>+<step>; END LOOP; 20

21 Queries General SELECT-FROM-WHERE queries are not permitted in PL/pgsql There are three ways to get the effect of a query: 1. Queries producing one value can be the expression in an assignment 2. Single-row SELECT... INTO 3. Cursors 21

22 Example: Assignment/Query Using local variable p and Sells(bar, beer, price), we can get the price Cafe Chino charges for Odense Classic by: p := (SELECT price FROM Sells WHERE bar = C.Ch AND beer = Od.Cl. ); 22

23 SELECT... INTO Another way to get the value of a query that returns one tuple is by placing INTO <variable> after the SELECT clause Example: SELECT price INTO p FROM Sells WHERE bar = C.Ch. AND beer = Od.Cl. ; 23

24 Cursors A cursor is essentially a tuple-variable that ranges over all tuples in the result of some query Declare a cursor c by: DECLARE c CURSOR FOR <query>; 24

25 Opening and Closing Cursors To use cursor c, we must issue the command: OPEN c; The query of c is evaluated, and c is set to point to the first tuple of the result When finished with c, issue command: CLOSE c; 25

26 Fetching Tuples From a Cursor To get the next tuple from cursor c, issue command: FETCH FROM c INTO x 1, x 2,,x n ; The x s are a list of variables, one for each component of the tuples referred to by c c is moved automatically to the next tuple 26

27 Breaking Cursor Loops (1) The usual way to use a cursor is to create a loop with a FETCH statement, and do something with each tuple fetched A tricky point is how we get out of the loop when the cursor has no more tuples to deliver 27

28 Breaking Cursor Loops (2) Many operations returns if a row has been found, changed, inserted, or deleted (SELECT INTO, UPDATE, INSERT, DELETE, FETCH) In plpgsql, we can get the value of the status in a variable called FOUND 28

29 Breaking Cursor Loops (3) The structure of a cursor loop is thus: <<cursorloop>> LOOP FETCH c INTO ; IF NOT FOUND THEN EXIT cursorloop; END IF; END LOOP; 29

30 Example: Cursor Let us write a procedure that examines Sells(bar, beer, price), and raises by 10 the price of all beers at Cafe Chino that are under 30 Yes, we could write this as a simple UPDATE, but the details are instructive anyway 30

31 The Needed Declarations CREATE FUNCTION RaisePrices() RETURNS VOID AS $$ DECLARE thebeer CHAR(20); theprice REAL; c CURSOR FOR (SELECT beer, price FROM Sells WHERE bar = C.Ch. ); Used to hold beer-price pairs when fetching through cursor c Returns Cafe Chino s price list 31

32 The Procedure Body BEGIN OPEN c; <<menuloop>> LOOP FETCH c INTO thebeer, theprice; EXIT menuloop WHEN NOT FOUND; IF theprice < 30 THEN UPDATE Sells SET price = theprice + 10 WHERE bar = C.Ch. AND beer = thebeer; END IF; END LOOP; CLOSE c; END;$$ LANGUAGE plpgsql; Check if the recent FETCH failed to get a tuple If Cafe Chino charges less than 30 for the beer, raise its price at at Cafe Chino by 10 32

33 Tuple-Valued Variables PL/pgsql allows a variable x to have a tuple type x R%ROWTYPE gives x the type of R s tuples R could be either a relation or a cursor x.a gives the value of the component for attribute a in the tuple x 33

34 Example: Tuple Type Repeat of RaisePrices() declarations with variable bp of type beer-price pairs CREATE FUNCTION RaisePrices() RETURNS VOID AS $$ DECLARE CURSOR c IS SELECT beer, price FROM Sells WHERE bar = C.Ch. ; bp c%rowtype; 34

35 RaisePrices() Body Using bp BEGIN OPEN c; LOOP FETCH c INTO bp; EXIT WHEN NOT FOUND; IF bp.price < 30 THEN UPDATE Sells SET price = bp.price + 10 WHERE bar = C.Ch. AND beer = bp.beer; END IF; END LOOP; CLOSE c; END; Components of bp are obtained with a dot and the attribute name 35

36 Database-Connection Libraries 36

37 Host/SQL Interfaces Via Libraries The third approach to connecting databases to conventional languages is to use library calls 1. C + CLI 2. Java + JDBC 3. PHP + PEAR/DB 37

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

39 Example: Amazon Database 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 39

40 Environments, Connections, Queries The database is, in many DB-access languages, an environment Database servers maintain some number of connections, so app servers can ask queries or perform modifications The app server issues statements: queries and modifications, usually 40

41 JDBC Java Database Connectivity (JDBC) is a library similar for accessing a DBMS with Java as the host language 221 drivers available: PostgreSQL, MySQL, Oracle, ODBC,

42 Making a Connection import java.sql.*;... Loaded by forname URL of the database your name, and password go here The JDBC classes Class.forName( org.postgresql.driver ); Connection mycon =... DriverManager.getConnection( ); The driver for postgresql; others exist 42

43 URL for PostgreSQL database jdbc:postgresql://<host>[:<port>]/ <database>?user=<user>& password=<password> Alternatively use getconnection variant: getconnection( jdbc:postgresql:// <host>[:<port>]/<database>, <user>, <password>); DriverManager.getConnection( jdbc:pos tgresql:// /petersk09, petersk09, geheim ); 43

44 Statements JDBC provides two classes: 1. Statement = an object that can accept a string that is a SQL statement and can execute such a string 2. PreparedStatement = an object that has an associated SQL statement ready to execute 44

45 Creating Statements The Connection class has methods to create Statements and PreparedStatements Statement stat1 = mycon.createstatement(); PreparedStatement stat2 = mycon.createstatement( ); SELECT beer, price FROM Sells + WHERE bar = C.Ch. createstatement with no argument returns a Statement; with one argument it returns a PreparedStatement 45

46 Executing SQL Statements JDBC distinguishes queries from modifications, which it calls updates Statement and PreparedStatement each have methods executequery and executeupdate For Statements: one argument the query or modification to be executed For PreparedStatements: no argument 46

47 Example: Update stat1 is a Statement We can use it to insert a tuple as: stat1.executeupdate( INSERT INTO Sells + VALUES( C.Ch., Eventyr,30) ); 47

48 Example: Query stat2 is a PreparedStatement holding the query SELECT beer, price FROM Sells WHERE bar = C.Ch. executequery returns an object of class ResultSet we ll examine it later The query: ResultSet menu = stat2.executequery(); 48

49 Accessing the ResultSet An object of type ResultSet is something like a cursor Method next() advances the cursor to the next tuple The first time next() is applied, it gets the first tuple If there are no more tuples, next() returns the value false 49

50 Accessing Components of Tuples When a ResultSet is referring to a tuple, we can get the components of that tuple by applying certain methods to the ResultSet Method getx (i ), where X is some type, and i is the component number, returns the value of that component The value must have type X 50

51 Example: Accessing Components Menu = ResultSet for query SELECT beer, price FROM Sells WHERE bar = C.Ch. Access beer and price from each tuple by: while (menu.next()) { } thebeer = menu.getstring(1); theprice = menu.getfloat(2); /*something with thebeer and theprice*/ 51

52 Important Details Reusing a Statement object results in the ResultSet being closed Always create new Statement objects using createstatement() or explicitly close ResultSets using the close method For transactions, for the Connection con use con.setautocommit(false) and explicitly con.commit() or con.rollback() If AutoCommit is false and there is no commit, closing the connection = rollback 52

53 PHP A language to be used for actions within HTML text Indicated by <?PHP code?>. DB library exists within PEAR (PHP Extension and Application Repository) Include with include(db.php) 53

54 Variables in PHP Must begin with $ OK not to declare a type for a variable But you give a variable a value that belongs to a class, in which case, methods of that class are available to it 54

55 String Values PHP solves a very important 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? PHP solution: Double quotes means replace; single quotes means do not 55

56 Example: Replace or Not? $100 = one hundred dollars ; $Peter = You owe me $100. ; $Lars = You owe me $100. ; Value of $Peter is You owe me $100, while the value of $Lars is You owe me one hundred dollars 56

57 PHP 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 57

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

59 Example: Associative Arrays An environment can be expressed as an associative array, e.g.: $myenv = array( phptype => pgsql, hostspec => localhost, port => 5432, database => petersk09, username => petersk09, password => geheim ); 59

60 Making a Connection With the DB library imported and the array $myenv available: $mycon = DB::connect($myEnv); Function connect in the DB library Class is Connection because it is returned by DB::connect() 60

61 Executing SQL Statements Method query applies to a Connection object It takes a string argument and returns a result Could be an error code or the relation returned by a query 61

62 Example: Executing a Query Find all the bars that sell a beer given by the variable $beer $beer = Od.Cl. ; Method application $result = $mycon->query( SELECT bar FROM Sells. WHERE beer = $beer ; ); Concatenation in PHP Remember this variable is replaced by its value. 62

63 Cursors in PHP The result of a query is the tuples returned Method fetchrow applies to the result and returns the next tuple, or FALSE if there is none 63

64 Example: Cursors while ($bar = $result->fetchrow()) { // do something with $bar } 64

65 Example: Tuple Cursors $bar = C.Ch. ; $menu = $mycon->query( SELECT beer, price FROM Sells WHERE bar = $bar ; ); while ($bp = $result->fetchrow()) { } print $bp[0]. for. $bp[1]; 65

Chapter 9 SQL in a server environment

Chapter 9 SQL in a server environment Chapter 9 SQL in a server environment SQL in a Programming Environment embedded SQL persistent stored modules Database-Connection Libraries Call-level interface (CLI) JDBC PHP Database connection The third

More information

Chapter 9 SQL in a server environment

Chapter 9 SQL in a server environment Chapter 9 SQL in a server environment SQL in a Programming Environment embedded SQL persistent stored modules Database-Connection Libraries Call-level interface (CLI) JDBC PHP SQL in Real Programs We have

More information

Database-Connection Libraries

Database-Connection Libraries Database-Connection Libraries CALL-LEVEL INTERFACE JAVA DATABASE CONNECTIVITY PHP PEAR/DB 1 An Aside: SQL Injection SQL queries are often constructed by programs. These queries may take constants from

More information

Database-Connection Libraries. Java Database Connectivity PHP

Database-Connection Libraries. Java Database Connectivity PHP Database-Connection Libraries Call-Level Interface Java Database Connectivity PHP 1 An Aside: SQL Injection SQL queries are often constructed by programs. These queries may take constants from user input.

More information

Databases 1. SQL/PSM and Oracle PL/SQL

Databases 1. SQL/PSM and Oracle PL/SQL Databases 1 SQL/PSM and Oracle PL/SQL SQL DDL (Data Definition Language) Defining a Database Schema Primary Keys, Foreign Keys Local and Global Constraints Defining Views Triggers 2 SQL DML (Database Modifications)

More information

Real SQL Programming Persistent Stored Modules (PSM)

Real SQL Programming Persistent Stored Modules (PSM) Real SQL Programming Persistent Stored Modules (PSM) Ullman-Widom: Adatbázisrendszerek Alapvetés. Második, átdolgozott kiadás, Panem, 2009 9.3. Az SQL és a befogadó nyelv közötti felület (sormutatók, cursors)

More information

Database Design and Programming

Database Design and Programming Database Design and Programming Jan Baumbach jan.baumbach@imada.sdu.dk http://www.baumbachlab.net JDBC Java Database Connectivity (JDBC) is a library similar for accessing a DBMS with Java as the host

More information

CSCD43: Database Systems Technology. Lecture 4

CSCD43: Database Systems Technology. Lecture 4 CSCD43: Database Systems Technology Lecture 4 Wael Aboulsaadat Acknowledgment: these slides are based on Prof. Garcia-Molina & Prof. Ullman slides accompanying the course s textbook. Steps in Database

More information

Non-interactive SQL. EECS Introduction to Database Management Systems

Non-interactive SQL. EECS Introduction to Database Management Systems Non-interactive SQL EECS3421 - Introduction to Database Management Systems Using a Database Interactive SQL: Statements typed in from terminal; DBMS outputs to screen. Interactive SQL is inadequate in

More information

Options. Real SQL Programming 1. Stored Procedures. Embedded SQL

Options. Real SQL Programming 1. Stored Procedures. Embedded SQL Real 1 Options 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

More information

Schedule. Feb. 12 (T) Advising Day. No class. Reminder: Midterm is Feb. 14 (TH) Today: Feb. 7 (TH) Feb. 21 (TH) Feb. 19 (T)

Schedule. Feb. 12 (T) Advising Day. No class. Reminder: Midterm is Feb. 14 (TH) Today: Feb. 7 (TH) Feb. 21 (TH) Feb. 19 (T) Schedule Today: Feb. 7 (TH) PL/SQL, Embedded SQL, CLI, JDBC. Read Sections 8.1, 8.3-8.5. Feb. 12 (T) Advising Day. No class. Reminder: Midterm is Feb. 14 (TH) Covers material through Feb. 7 (TH) lecture

More information

DATABASE DESIGN - 1DL400

DATABASE DESIGN - 1DL400 DATABASE DESIGN - 1DL400 Fall 2015 A course on modern database systems http://www.it.uu.se/research/group/udbl/kurser/dbii_ht15 Kjell Orsborn Uppsala Database Laboratory Department of Information Technology,

More information

Outline. CS 235: Introduction to Databases. DB Application Programming. Interface Solutions. Basic PSM Form. Persistent Stored Modules

Outline. CS 235: Introduction to Databases. DB Application Programming. Interface Solutions. Basic PSM Form. Persistent Stored Modules Outline CS 235: Introduction to Databases Svetlozar Nestorov Database application programming SQL limitations SQL Persistent, Stored Modules (PSM) Extension of SQL PL/SQL: Oracle s version of PSM Lecture

More information

Database Applications. SQL/PSM Embedded SQL JDBC

Database Applications. SQL/PSM Embedded SQL JDBC Database Applications SQL/PSM Embedded SQL JDBC 1 Course Objectives Design Construction Applications Usage 2 Course Objectives Interfacing When the course is through, you should Know how to connect to

More information

Likesèdrinker, beerè. Sellsèbar, beer, priceè. Frequentsèdrinker, barè

Likesèdrinker, beerè. Sellsèbar, beer, priceè. Frequentsèdrinker, barè Modication to Views Via Triggers Oracle allows us to ëintercept" a modication to a view through an instead-of trigger Example Likesèdrinker, beerè Sellsèbar, beer, priceè Frequentsèdrinker, barè CREATE

More information

Embedded SQL. csc343, Introduction to Databases Diane Horton with examples from Ullman and Widom Fall 2014

Embedded SQL. csc343, Introduction to Databases Diane Horton with examples from Ullman and Widom Fall 2014 Embedded SQL csc343, Introduction to Databases Diane Horton with examples from Ullman and Widom Fall 2014 Problems with using interactive SQL Standard SQL is not Turing-complete. E.g., Two profs are colleagues

More information

Embedded SQL. csc343, Introduction to Databases Renée J. Miller and Fatemeh Nargesian and Sina Meraji Winter 2018

Embedded SQL. csc343, Introduction to Databases Renée J. Miller and Fatemeh Nargesian and Sina Meraji Winter 2018 Embedded SQL csc343, Introduction to Databases Renée J. Miller and Fatemeh Nargesian and Sina Meraji Winter 2018 Problems with using interactive SQL Standard SQL is not Turing-complete. E.g., Two profs

More information

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe Chapter 10 Outline Database Programming: Techniques and Issues Embedded SQL, Dynamic SQL, and SQLJ Database Programming with Function Calls: SQL/CLI and JDBC Database Stored Procedures and SQL/PSM Comparing

More information

Working with Databases and Java

Working with Databases and Java Working with Databases and Java Pedro Contreras Department of Computer Science Royal Holloway, University of London January 30, 2008 Outline Introduction to relational databases Introduction to Structured

More information

Chapter 13 Introduction to SQL Programming Techniques

Chapter 13 Introduction to SQL Programming Techniques Chapter 13 Introduction to SQL Programming Techniques Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13 Outline Database Programming: Techniques and Issues Embedded

More information

Programming in Java

Programming in Java 320341 Programming in Java Fall Semester 2014 Lecture 16: Introduction to Database Programming Instructor: Slides: Jürgen Schönwälder Bendick Mahleko Objectives This lecture introduces the following -

More information

Lab # 9. Java to Database Connection

Lab # 9. Java to Database Connection Islamic University of Gaza Faculty of Engineering Department of Computer Engineering ECOM 4113: Lab # 9 Java to Database Connection Eng. Haneen El-Masry December, 2014 2 Objective In this lab, we turn

More information

Assign expressions to declared variables with :=. END IF; EXIT WHEN éconditioné END LOOP;

Assign expressions to declared variables with :=. END IF; EXIT WHEN éconditioné END LOOP; Assignment Assign expressions to declared variables with :=. Branches IF éconditioné THEN éstatementèsèé ELSE éstatementèsèé END IF; But in nests, use ELSIF in place of ELSE IF. Loops LOOP... EXIT WHEN

More information

EMBEDDED SQL. SE 3DB3 Fall 2016 MICHAEL LIUT DEPARTMENT OF COMPUTING AND SOFTWARE MCMASTER UNIVERSITY

EMBEDDED SQL. SE 3DB3 Fall 2016 MICHAEL LIUT DEPARTMENT OF COMPUTING AND SOFTWARE MCMASTER UNIVERSITY EMBEDDED SQL MICHAEL LIUT (LIUTM@MCMASTER.CA) DEPARTMENT OF COMPUTING AND SOFTWARE MCMASTER UNIVERSITY SE 3DB3 Fall 2016 (Slides adapted from Dr. Fei Chiang, Diane Horton, examples from J. Ullman, J. Widom)

More information

SQL in a Server Environment

SQL in a Server Environment SQL in a Server Environment Vaidė Narváez Computer Information Systems January 13th, 2011 The Three-Tier Architecture Application logic components Copyright c 2009 Pearson Education, Inc. Publishing as

More information

JDBC Architecture. JDBC API: This provides the application-to- JDBC Manager connection.

JDBC Architecture. JDBC API: This provides the application-to- JDBC Manager connection. JDBC PROGRAMMING JDBC JDBC Java DataBase Connectivity Useful for database driven applications Standard API for accessing relational databases Compatible with wide range of databases Current Version JDBC

More information

DataBase Lab JAVA-DATABASE CONNECTION. Eng. Haneen El-masry

DataBase Lab JAVA-DATABASE CONNECTION. Eng. Haneen El-masry In the name of Allah Islamic University of Gaza Faculty of Engineering Computer Engineering Department ECOM 4113 DataBase Lab Lab # 9 JAVA-DATABASE CONNECTION El-masry 2013 Objective In this lab, we turn

More information

SQL DML and DB Applications, JDBC

SQL DML and DB Applications, JDBC SQL DML and DB Applications, JDBC Week 4.2 Week 4 MIE253-Consens 1 Schedule Week Date Lecture Topic 1 Jan 9 Introduction to Data Management 2 Jan 16 The Relational Model 3 Jan. 23 Constraints and SQL DDL

More information

Why SQL? SQL is a very-high-level language. Database management system figures out best way to execute query

Why SQL? SQL is a very-high-level language. Database management system figures out best way to execute query Basic SQL Queries 1 Why SQL? SQL is a very-high-level language Say what to do rather than how to do it Avoid a lot of data-manipulation details needed in procedural languages like C++ or Java Database

More information

Running SQL in Java and PHP

Running SQL in Java and PHP Running SQL in Java and PHP FCDB 9.6 9.7 Dr. Chris Mayfield Department of Computer Science James Madison University Mar 01, 2017 Introduction to JDBC JDBC = Java Database Connectivity 1. Connect to the

More information

Subqueries. Must use a tuple-variable to name tuples of the result

Subqueries. Must use a tuple-variable to name tuples of the result Subqueries A parenthesized SELECT-FROM-WHERE statement (subquery) can be used as a value in a number of places, including FROM and WHERE clauses Example: in place of a relation in the FROM clause, we can

More information

SQL in Programming Languages Read chapter 5 of Atzeni et al. BD: Modelli e Linguaggi di Interrogazione and section 8.

SQL in Programming Languages Read chapter 5 of Atzeni et al. BD: Modelli e Linguaggi di Interrogazione and section 8. SQL in Programming Languages Read chapter 5 of Atzeni et al. BD: Modelli e Linguaggi di Interrogazione and section 8.4 of Garcia-Molina Slides derived from those by Jeffrey D. Ullman SQL and Programming

More information

CSCI/CMPE Object-Oriented Programming in Java JDBC. Dongchul Kim. Department of Computer Science University of Texas Rio Grande Valley

CSCI/CMPE Object-Oriented Programming in Java JDBC. Dongchul Kim. Department of Computer Science University of Texas Rio Grande Valley CSCI/CMPE 3326 Object-Oriented Programming in Java JDBC Dongchul Kim Department of Computer Science University of Texas Rio Grande Valley Introduction to Database Management Systems Storing data in traditional

More information

Overview. Database Application Development. SQL in Application Code. SQL in Application Code (cont.)

Overview. Database Application Development. SQL in Application Code. SQL in Application Code (cont.) Overview Database Application Development Chapter 6 Concepts covered in this lecture: SQL in application code Embedded SQL Cursors Dynamic SQL JDBC SQLJ Stored procedures Database Management Systems 3ed

More information

Database Application Development

Database Application Development Database Application Development Chapter 6 Database Management Systems 3ed 1 Overview Concepts covered in this lecture: SQL in application code Embedded SQL Cursors Dynamic SQL JDBC SQLJ Stored procedures

More information

Database Application Development

Database Application Development Database Application Development Chapter 6 Database Management Systems 3ed 1 Overview Concepts covered in this lecture: SQL in application code Embedded SQL Cursors Dynamic SQL JDBC SQLJ Stored procedures

More information

Running SQL in Java and PHP

Running SQL in Java and PHP Running SQL in Java and PHP FCDB 9.6 9.7 Dr. Chris Mayfield Department of Computer Science James Madison University Feb 28, 2018 Introduction to JDBC JDBC = Java Database Connectivity 1. Connect to the

More information

JDBC, Transactions. Niklas Fors JDBC 1 / 38

JDBC, Transactions. Niklas Fors JDBC 1 / 38 JDBC, Transactions SQL in Programs Embedded SQL and Dynamic SQL JDBC Drivers, Connections, Statements, Prepared Statements Updates, Queries, Result Sets Transactions Niklas Fors (niklas.fors@cs.lth.se)

More information

SQL: Programming Midterm in class next Thursday (October 5)

SQL: Programming Midterm in class next Thursday (October 5) Announcements (September 28) 2 Homework #1 graded Homework #2 due today Solution available this weekend SQL: Programming Midterm in class next Thursday (October 5) Open book, open notes Format similar

More information

ITCS Implementation. Jing Yang 2010 Fall. Class 14: Introduction to SQL Programming Techniques (Ch13) Outline

ITCS Implementation. Jing Yang 2010 Fall. Class 14: Introduction to SQL Programming Techniques (Ch13) Outline ITCS 3160 Data Base Design and Implementation Jing Yang 2010 Fall Class 14: Introduction to SQL Programming Techniques (Ch13) Outline Database Programming: Techniques and Issues Three approaches: Embedded

More information

INTRODUCTION TO JDBC - Revised spring

INTRODUCTION TO JDBC - Revised spring INTRODUCTION TO JDBC - Revised spring 2004 - 1 What is JDBC? Java Database Connectivity (JDBC) is a package in the Java programming language and consists of several Java classes that deal with database

More information

O ne of the most important features of JavaServer

O ne of the most important features of JavaServer INTRODUCTION TO DATABASES O ne of the most important features of JavaServer Pages technology is the ability to connect to a Databases store and efficiently manage large collections of information. JSP

More information

You write standard JDBC API application and plug in the appropriate JDBC driver for the database the you want to use. Java applet, app or servlets

You write standard JDBC API application and plug in the appropriate JDBC driver for the database the you want to use. Java applet, app or servlets JDBC Stands for Java Database Connectivity, is an API specification that defines the following: 1. How to interact with database/data-source from Java applets, apps, servlets 2. How to use JDBC drivers

More information

The Web Application Developer s. Red Hat Database. View. October 30, Webcast. Patrick Macdonald, Fernando Nasser. Red Hat Database Engineering

The Web Application Developer s. Red Hat Database. View. October 30, Webcast. Patrick Macdonald, Fernando Nasser. Red Hat Database Engineering Red Hat Database The Web Application Developer s View Webcast October 30, 2001 Patrick Macdonald, Fernando Nasser Liam Stewart, Neil Padgett Red Hat Database Engineering Agenda Red Hat Database Web Interaction

More information

Pieter van den Hombergh. March 25, 2018

Pieter van den Hombergh. March 25, 2018 ergh Fontys Hogeschool voor Techniek en Logistiek March 25, 2018 ergh/fhtenl March 25, 2018 1/25 JDBC JDBC is a Java database connectivity technology (Java Standard Edition platform) from Oracle Corporation.

More information

Part I: Stored Procedures. Introduction to SQL Programming Techniques. CSC 375, Fall 2017

Part I: Stored Procedures. Introduction to SQL Programming Techniques. CSC 375, Fall 2017 Introduction to SQL Programming Techniques CSC 375, Fall 2017 The Six Phases of a Project: Enthusiasm Disillusionment Panic Search for the Guilty Punishment of the Innocent Praise for non-participants

More information

Logging and Recovery. 444 Section, April 23, 2009

Logging and Recovery. 444 Section, April 23, 2009 Logging and Recovery 444 Section, April 23, 2009 Reminders Project 2 out: Due Wednesday, Nov. 4, 2009 Homework 1: Due Wednesday, Oct. 28, 2009 Outline Project 2: JDBC ACID: Recovery Undo, Redo logging

More information

JDBC. Sun Microsystems has included JDBC API as a part of J2SDK to develop Java applications that can communicate with databases.

JDBC. Sun Microsystems has included JDBC API as a part of J2SDK to develop Java applications that can communicate with databases. JDBC The JDBC TM API is the application programming interface that provides universal data access for the Java TM platform. In other words, the JDBC API is used to work with a relational database or other

More information

Constraints and Triggers

Constraints and Triggers Constraints 1 Constraints and Triggers A constraint is a relationship among data elements that the DBMS is required to enforce Example: key constraints Triggers are only executed when a specified condition

More information

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

Database Programming. Week 9. *Some of the slides in this lecture are created by Prof. Ian Horrocks from University of Oxford Database Programming Week 9 *Some of the slides in this lecture are created by Prof. Ian Horrocks from University of Oxford SQL in Real Programs We have seen only how SQL is used at the generic query interface

More information

INTRODUCTION TO JDBC - Revised Spring

INTRODUCTION TO JDBC - Revised Spring INTRODUCTION TO JDBC - Revised Spring 2006 - 1 What is JDBC? Java Database Connectivity (JDBC) is an Application Programmers Interface (API) that defines how a Java program can connect and exchange data

More information

From E/R Diagrams to Relations

From E/R Diagrams to Relations From E/R Diagrams to Relations Entity set relation Attributes attributes Relationships relations whose attributes are only: The keys of the connected entity sets Attributes of the relationship itself 1

More information

ERwin and JDBC. Mar. 6, 2007 Myoung Ho Kim

ERwin and JDBC. Mar. 6, 2007 Myoung Ho Kim ERwin and JDBC Mar. 6, 2007 Myoung Ho Kim ERwin ERwin a popular commercial ER modeling tool» other tools: Dia (open source), Visio, ConceptDraw, etc. supports database schema generation 2 ERwin UI 3 Data

More information

Database Application Development

Database Application Development Database Application Development Linda Wu (CMPT 354 2004-2) Topics SQL in application code Embedded SQL JDBC SQLJ Stored procedures Chapter 6 CMPT 354 2004-2 2 SQL in Application Code SQL commands can

More information

This lecture. PHP tags

This lecture. PHP tags This lecture Databases I This covers the (absolute) basics of and how to connect to a database using MDB2. (GF Royle 2006-8, N Spadaccini 2008) I 1 / 24 (GF Royle 2006-8, N Spadaccini 2008) I 2 / 24 What

More information

Databases PHP I. (GF Royle, N Spadaccini ) PHP I 1 / 24

Databases PHP I. (GF Royle, N Spadaccini ) PHP I 1 / 24 Databases PHP I (GF Royle, N Spadaccini 2006-2010) PHP I 1 / 24 This lecture This covers the (absolute) basics of PHP and how to connect to a database using MDB2. (GF Royle, N Spadaccini 2006-2010) PHP

More information

CSE 308. Database Issues. Goals. Separate the application code from the database

CSE 308. Database Issues. Goals. Separate the application code from the database CSE 308 Database Issues The following databases are created with password as changeit anticyber cyber cedar dogwood elm clan Goals Separate the application code from the database Encourages you to think

More information

Cyrus Shahabi Computer Science Department University of Southern California C. Shahabi

Cyrus Shahabi Computer Science Department University of Southern California C. Shahabi Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California shahabi@usc.edu 1 Overview JDBC Package Connecting to databases with JDBC Executing

More information

Application Programming for Relational Databases

Application Programming for Relational Databases Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California shahabi@usc.edu 1 Overview JDBC Package Connecting to databases with JDBC Executing

More information

Database Application Development

Database Application Development CS 461: Database Systems Database Application Development supplementary material: Database Management Systems Sec. 6.2, 6.3 DBUtils.java, Student.java, Registrar.java, RegistrarServlet.java, PgRegistrar.sql

More information

CSC System Development with Java. Database Connection. Department of Statistics and Computer Science. Budditha Hettige

CSC System Development with Java. Database Connection. Department of Statistics and Computer Science. Budditha Hettige CSC 308 2.0 System Development with Java Database Connection Budditha Hettige Department of Statistics and Computer Science Budditha Hettige 1 From database to Java There are many brands of database: Microsoft

More information

Embedded SQL. Introduction

Embedded SQL. Introduction Embedded SQL Davood Rafiei 1 Introduction Basic Idea: Use SQL statements inside a host language (C, C++, Java, ). Advantages: Can do all the fancy things you do in C/C++/Java. Still have the power of SQL.

More information

Embedded SQL. Davood Rafiei

Embedded SQL. Davood Rafiei Embedded SQL Davood Rafiei 1 Introduction Basic Idea: Use SQL statements inside a host language (C, C++, Java, ). Advantages: Can do all the fancy things you do in C/C++/Java. Still have the power of SQL.

More information

PERSİSTENCE OBJECT RELATİON MAPPİNG

PERSİSTENCE OBJECT RELATİON MAPPİNG PERSİSTENCE Most of the applications require storing and retrieving objects in a persistent storage mechanism. This chapter introduces how to store and retrieve information in a persistent storage with

More information

UNIT III - JDBC Two Marks

UNIT III - JDBC Two Marks UNIT III - JDBC Two Marks 1.What is JDBC? JDBC stands for Java Database Connectivity, which is a standard Java API for databaseindependent connectivity between the Java programming language and a wide

More information

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science mluckner@mini.pw.edu.pl http://www.mini.pw.edu.pl/~lucknerm } JDBC ("Java Database Connectivity ) is a set

More information

MANTHLY TEST SEPTEMBER 2017 QUESTION BANK CLASS: XII SUBJECT: INFORMATICS PRACTICES (065)

MANTHLY TEST SEPTEMBER 2017 QUESTION BANK CLASS: XII SUBJECT: INFORMATICS PRACTICES (065) MANTHLY TEST SEPTEMBER 2017 QUESTION BANK CLASS: XII SUBJECT: INFORMATICS PRACTICES (065) DATABASE CONNECTIVITY TO MYSQL Level- I Questions 1. What is the importance of java.sql.*; in java jdbc connection?

More information

e-pg Pathshala Subject: Computer Science Paper: Web Technology Module: JDBC INTRODUCTION Module No: CS/WT/26 Quadrant 2 e-text

e-pg Pathshala Subject: Computer Science Paper: Web Technology Module: JDBC INTRODUCTION Module No: CS/WT/26 Quadrant 2 e-text e-pg Pathshala Subject: Computer Science Paper: Web Technology Module: JDBC INTRODUCTION Module No: CS/WT/26 Quadrant 2 e-text Learning Objectives This module gives an introduction about Java Database

More information

Contains slides made by Naci Akkøk, Pål Halvorsen, Arthur M. Keller, Vera Goebel

Contains slides made by Naci Akkøk, Pål Halvorsen, Arthur M. Keller, Vera Goebel SQL-99 Contains slides made by Naci Akkøk, Pål Halvorsen, Arthur M. Keller, Vera Goebel SQL-99 user-defined types (UDTs) methods for UDTs declarations references operations Overview 2 SQL Development SQL-86

More information

Database Design and Programming

Database Design and Programming Database Design and Programming Jan Baumbach jan.baumbach@imada.sdu.dk http://www.baumbachlab.net Example: EXISTS Set of beers with the same manf as b1, but not the same beer SELECT name FROM Beers b1

More information

Top 50 JDBC Interview Questions and Answers

Top 50 JDBC Interview Questions and Answers Top 50 JDBC Interview Questions and Answers 1) What is the JDBC? JDBC stands for Java Database Connectivity. JDBC is a Java API that communicates with the database and execute SQLquery. 2) What is a JDBC

More information

Discuss setting up JDBC connectivity. Demonstrate a JDBC program Discuss and demonstrate methods associated with JDBC connectivity

Discuss setting up JDBC connectivity. Demonstrate a JDBC program Discuss and demonstrate methods associated with JDBC connectivity Objectives Discuss setting up JDBC connectivity. Demonstrate a JDBC program Discuss and demonstrate methods associated with JDBC connectivity Setting Up JDBC Before you can begin to utilize JDBC, you must

More information

Outline. Lecture 10: Database Connectivity -JDBC. Java Persistence. Persistence via Database

Outline. Lecture 10: Database Connectivity -JDBC. Java Persistence. Persistence via Database Outline Lecture 10: Database Connectivity -JDBC Persistence via Database JDBC (Java Database Connectivity) JDBC API Wendy Liu CSC309F Fall 2007 1 2 Java Persistence Persistence via Database JDBC (Java

More information

SQL: Programming. Announcements (September 25) Motivation. CPS 116 Introduction to Database Systems. Pros and cons of SQL.

SQL: Programming. Announcements (September 25) Motivation. CPS 116 Introduction to Database Systems. Pros and cons of SQL. SQL: Programming CPS 116 Introduction to Database Systems Announcements (September 25) 2 Homework #2 due this Thursday Submit to Yi not through Jun s office door Solution available this weekend No class

More information

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe Chapter 11 Outline A Simple PHP Example Overview of Basic Features of PHP Overview of PHP Database Programming Slide 11-2 Web Database Programming Using PHP Techniques for programming dynamic features

More information

Kyle Brown Knowledge Systems Corporation by Kyle Brown and Knowledge Systems Corporation

Kyle Brown Knowledge Systems Corporation by Kyle Brown and Knowledge Systems Corporation Kyle Brown Knowledge Systems Corporation 1 What is the JDBC? What other persistence mechanisms are available? What facilities does it offer? How is it used? 2 JDBC is the Java DataBase Connectivity specification

More information

Database Application Development

Database Application Development CS 500: Fundamentals of Databases Database Application Development supplementary material: Database Management Systems Sec. 6.2, 6.3 DBUtils.java, Student.java, Registrar.java, RegistrarServlet.java, PgRegistrar.sql

More information

Chapter 11 Outline. A Simple PHP Example Overview of Basic Features of PHP Overview of PHP Database Programming. Slide 11-2

Chapter 11 Outline. A Simple PHP Example Overview of Basic Features of PHP Overview of PHP Database Programming. Slide 11-2 Chapter 11 Outline A Simple PHP Example Overview of Basic Features of PHP Overview of PHP Database Programming Slide 11-2 1 Web Database Programming Using PHP Techniques for programming dynamic features

More information

Enterprise Java Unit 1- Chapter 6 Prof. Sujata Rizal

Enterprise Java Unit 1- Chapter 6 Prof. Sujata Rizal Introduction JDBC is a Java standard that provides the interface for connecting from Java to relational databases. The JDBC standard is defined by Sun Microsystems and implemented through the standard

More information

JAVA AND DATABASES. Summer 2018

JAVA AND DATABASES. Summer 2018 JAVA AND DATABASES Summer 2018 JDBC JDBC (Java Database Connectivity) an API for working with databases in Java (works with any tabular data, but focuses on relational databases) Works with 3 basic actions:

More information

Database Application Development

Database Application Development Database Application Development Chapter 6 PSM (Stored Procedures) 1 Stored Procedures What is a stored procedure: SQL allows you to define procedures and functions and store in the DB server Program executed

More information

Chapter 16: Databases

Chapter 16: Databases Chapter 16: Databases Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 16 discusses the following main topics: Introduction to Database

More information

13 Creation and Manipulation of Tables and Databases

13 Creation and Manipulation of Tables and Databases 150.420 Informationslogistik SQL Handout No. 9 SS 2013 13 Creation and Manipulation of Tables and Databases 13.1 Creation and Deletion Databases can be created and deleted using respectively. CREATE DATABASE

More information

Database Programming Overview. COSC 304 Introduction to Database Systems. Database Programming. JDBC Interfaces. JDBC Overview

Database Programming Overview. COSC 304 Introduction to Database Systems. Database Programming. JDBC Interfaces. JDBC Overview COSC 304 Introduction to Database Systems Database Programming Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Database Programming Overview Most user interaction with

More information

Design Techniques. 1. Avoid redundancy 2. Limit the use of weak entity sets 3. Don t use an entity set when an attribute will do

Design Techniques. 1. Avoid redundancy 2. Limit the use of weak entity sets 3. Don t use an entity set when an attribute will do Design Techniques 1. Avoid redundancy 2. Limit the use of weak entity sets 3. Don t use an entity set when an attribute will do 1 Avoiding Redundancy Redundancy = saying the same thing in two (or more)

More information

CGS 3066: Spring 2017 SQL Reference

CGS 3066: Spring 2017 SQL Reference CGS 3066: Spring 2017 SQL Reference Can also be used as a study guide. Only covers topics discussed in class. This is by no means a complete guide to SQL. Database accounts are being set up for all students

More information

Introduction to SQL & Database Application Development Using Java

Introduction to SQL & Database Application Development Using Java Introduction to SQL & Database Application Development Using Java By Alan Andrea The purpose of this paper is to give an introduction to relational database design and sql with a follow up on how these

More information

JDBC Drivers Type. JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server.

JDBC Drivers Type. JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server. JDBC Drivers Type 1 What is JDBC Driver? JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server. For example, using JDBC drivers enable you to open database

More information

Database Management

Database Management Database Management - 2013 Model Answers 1. a. A cyclic relationship type (also called recursive) is a relationship type between two occurrences of the same entity type. With each entity type in a cyclic

More information

COP4540 TUTORIAL PROFESSOR: DR SHU-CHING CHEN TA: H S IN-YU HA

COP4540 TUTORIAL PROFESSOR: DR SHU-CHING CHEN TA: H S IN-YU HA COP4540 TUTORIAL PROFESSOR: DR SHU-CHING CHEN TA: H S IN-YU HA OUTLINE Postgresql installation Introduction of JDBC Stored Procedure POSTGRES INSTALLATION (1) Extract the source file Start the configuration

More information

PL/SQL, Embedded SQL. Lecture #14 Autumn, Fall, 2001, LRX

PL/SQL, Embedded SQL. Lecture #14 Autumn, Fall, 2001, LRX PL/SQL, Embedded SQL Lecture #14 Autumn, 2001 Fa, 2001, LRX #14 PL/SQL,Embedded SQL HUST,Wuhan,China 402 PL/SQL Found ony in the Orace SQL processor (sqpus). A compromise between competey procedura programming

More information

Database connectivity (II)

Database connectivity (II) Lecture (07) Database connectivity (II) Dr. Ahmed ElShafee 1 Dr. Ahmed ElShafee, ACU Spring 2011, Distributed Systems Agenda Connecting DB 2 Dr. Ahmed ElShafee, ACU Spring 2011, Distributed Systems The

More information

SQL: Programming. Introduction to Databases CompSci 316 Fall 2017

SQL: Programming. Introduction to Databases CompSci 316 Fall 2017 SQL: Programming Introduction to Databases CompSci 316 Fall 2017 2 Announcements (Thu., Oct. 12) Project milestone #1 due tonight Only one member per team needs to submit Remember members.txt Midterm is

More information

Lecture 9&10 JDBC. Mechanism. Some Warnings. Notes. Style. Introductory Databases SSC Introduction to DataBases 1.

Lecture 9&10 JDBC. Mechanism. Some Warnings. Notes. Style. Introductory Databases SSC Introduction to DataBases 1. Lecture 9&10 JDBC Java and SQL Basics Data Manipulation How to do it patterns etc. Transactions Summary JDBC provides A mechanism for to database systems An API for: Managing this Sending s to the DB Receiving

More information

SQL Stored Programs. You Can Not Do Everything in SQL SQL/PSM Cursors Recursion Triggers. Niklas Fors Stored Programs 1 / 21

SQL Stored Programs. You Can Not Do Everything in SQL SQL/PSM Cursors Recursion Triggers. Niklas Fors Stored Programs 1 / 21 SQL Stored Programs You Can Not Do Everything in SQL SQL/PSM Cursors Recursion Triggers Niklas Fors (niklas.fors@cs.lth.se) Stored Programs 1 / 21 Stored Programs SQL is not Turing complete so there are

More information

SQL from Applications

SQL from Applications SQL from Applications UVic C SC 370 Dr. Daniel M. German Department of Computer Science June 4, 2003 Version: 1.1.0 6 1 SQL from Applications (1.1.0) CSC 370 dmgerman@uvic.ca Overview Embedded SQL JDBC

More information

CS54100: Database Systems

CS54100: Database Systems CS54100: Database Systems SQL DDL 27 January 2012 Prof. Chris Clifton Defining a Database Schema CREATE TABLE name (list of elements). Principal elements are attributes and their types, but key declarations

More information

13.1 Relational Databases (continued) 13.1 Relational Databases. - Logical model

13.1 Relational Databases (continued) 13.1 Relational Databases. - Logical model 13.1 Relational Databases 13.1 Relational Databases (continued) - A relational database is a collection of tables of data, each of which has one special column that stores the primary keys of the table

More information

13.1 Relational Databases

13.1 Relational Databases 13.1 Relational Databases - A relational database is a collection of tables of data, each of which has one special column that stores the primary keys of the table - Designing a relational database for

More information

Questions and Answers. A. A DataSource is the basic service for managing a set of JDBC drivers.

Questions and Answers. A. A DataSource is the basic service for managing a set of JDBC drivers. Q.1) What is, in terms of JDBC, a DataSource? A. A DataSource is the basic service for managing a set of JDBC drivers B. A DataSource is the Java representation of a physical data source C. A DataSource

More information