SQL: Programming. Introduction to Databases CompSci 316 Fall 2014



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

CS346: Database Programming.

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

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

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

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

Real SQL Programming 1

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

Programming Database lectures for mathema

12 Embedding SQL in Programming languages

More SQL: Assertions, Views, and Programming Techniques

12 Embedding SQL in Programming languages

SQL and programming languages

SQL/PSM. Outline. Database Application Development Oracle PL/SQL. Why Stored Procedures? Stored Procedures PL/SQL. Embedded SQL Dynamic SQL

Database Access via Programming Languages

24 ottobre 2013.openerp.it XML-RPC vs Psycopg2 Dr. Piero Cecchi. OpenERP Analisi Prestazionale Python script XML-RPC vs Psycopg2

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

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

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

Maintaining Stored Procedures in Database Application

The JAVA Way: JDBC and SQLJ

Statement Level Interface. Call Level Interface. Static SQL. Status. Connections. Transactions. To connect to an SQL database, use a connect statement

Embedded SQL programming

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

14 Triggers / Embedded SQL

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

Database Access from a Programming Language:

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

Embedded SQL. Unit 5.1. Dr Gordon Russell, Napier University

What is ODBC? Database Connectivity ODBC, JDBC and SQLJ. ODBC Architecture. More on ODBC. JDBC vs ODBC. What is JDBC?

Database programming made easier Master thesis of Roland Balk

Chapter 9 Java and SQL. Wang Yang wyang@njnet.edu.cn

Database Application Development. Overview. SQL in Application Code. Chapter 6

5.1 Database Schema Schema Generation in SQL

Embedding SQL in High Level Language Programs

Chapter 13: Program Development and Programming Languages

1 SQL Data Types and Schemas

Mimer SQL. Programmer s Manual. Version 8.2 Copyright 2000 Mimer Information Technology AB

Why Is This Important? Database Application Development. SQL in Application Code. Overview. SQL in Application Code (Contd.

Guide to SQL Programming: SQL:1999 and Oracle Rdb V7.1

A Brief Introduction to MySQL

1 File Processing Systems

Intro to Embedded SQL Programming for ILE RPG Developers

Database Application Developer Tools Using Static Analysis and Dynamic Profiling

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Chapter 2 Database System Concepts and Architecture

Writing MySQL Scripts With Python's DB-API Interface

N3458: Simple Database Integration in C++11

Overview. Database Application Development. SQL in Application Code (Contd.) SQL in Application Code. Embedded SQL. Embedded SQL: Variables

McGraw-Hill The McGraw-Hill Companies, Inc.,

CSC 443 Database Management Systems. The SQL Programming Language

CSE 530A Database Management Systems. Introduction. Washington University Fall 2013

Database Design and Programming

Achieving Database Interoperability Across Data Access APIs through SQL Up-leveling

types, but key declarations and constraints Similar CREATE X commands for other schema ëdrop X name" deletes the created element of beer VARCHARè20è,

The Import & Export of Data from a Database

SAP HANA SQLScript Reference

Using SQL in RPG Programs: An Introduction

Micro Focus Database Connectors

database abstraction layer database abstraction layers in PHP Lukas Smith BackendMedia

SQL Tables, Keys, Views, Indexes

Darshan Institute of Engineering & Technology PL_SQL

Making Standard ML a Practical Database Programming Language

SQL and Java. Database Systems Lecture 19 Natasha Alechina

Duration Vendor Audience 5 Days Oracle Developers, Technical Consultants, Database Administrators and System Analysts

Web Applications Security: SQL Injection Attack

Object Oriented Software Design

Persistent Stored Modules (Stored Procedures) : PSM

SQL Server Database Coding Standards and Guidelines

Programming in Python V: Accessing a Database

Week 5: Embedded SQL. Embedded SQL 4. Application Program. Interactive vs. Non-Interactive SQL. Update Statements

Databases 2011 The Relational Model and SQL

Introduction to Microsoft Access 2003

How to Improve Database Connectivity With the Data Tools Platform. John Graham (Sybase Data Tooling) Brian Payton (IBM Information Management)

ERserver. DB2 Universal Database for iseries SQL Programming with Host Languages. iseries. Version 5

Database Programming with PL/SQL: Learning Objectives

Client vs. Server Implementations of Mitigating XSS Security Threats on Web Applications

SQL Injection Vulnerabilities in Desktop Applications

Database System Architecture & System Catalog Instructor: Mourad Benchikh Text Books: Elmasri & Navathe Chap. 17 Silberschatz & Korth Chap.

Introduction to Python

PostgreSQL Functions By Example

Project 2: Web Security Pitfalls

InterBase 6. Embedded SQL Guide. Borland/INPRISE. 100 Enterprise Way, Scotts Valley, CA

Chapter 13: Program Development and Programming Languages

dbext for Vim David Fishburn h5p://

OBJECTS AND DATABASES. CS121: Introduction to Relational Database Systems Fall 2015 Lecture 21

Elena Baralis, Silvia Chiusano Politecnico di Torino. Pag. 1. Active database systems. Triggers. Triggers. Active database systems.

PL/SQL Overview. Basic Structure and Syntax of PL/SQL

CHAPTER 5 INTELLIGENT TECHNIQUES TO PREVENT SQL INJECTION ATTACKS

PHP Tutorial From beginner to master

DATABASE SYSTEM CONCEPTS AND ARCHITECTURE CHAPTER 2

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

Database Management System Choices. Introduction To Database Systems CSE 373 Spring 2013

COSC344 Database Theory and Applications. Java and SQL. Lecture 12

Transcription:

SQL: Programming Introduction to Databases CompSci 316 Fall 2014

2 Announcements (Tue., Oct. 7) Homework #2 due today midnight Sample solution to be posted by tomorrow evening Midterm in class this Thursday Open-book, open-notes Same format as the sample midterm (posted on Sakai) Project milestone #1 due next Thursday

3 Motivation Pros and cons of SQL Very high-level, possible to optimize Not intended for general-purpose computation Solutions Augment SQL with constructs from general-purpose programming languages E.g.: SQL/PSM Use SQL together with general-purpose programming languages E.g.: Python DB API, JDBC, embedded SQL Extend general-purpose programming languages with SQL-like constructs E.g.: LINQ (Language Integrated Query for.net)

4 An impedance mismatch SQL operates on a set of records at a time Typical low-level general-purpose programming languages operate on one record at a time Solution: cursor Open(a result table): position the cursor before the first row Get next: move the cursor to the next row and return that row; raise a flag if there is no such row Close: clean up and release DBMS resources Found in virtually every database language/api With slightly different syntaxes Some support more positioning and movement options, modification at the current position, etc.

5 Augmenting SQL: SQL/PSM PSM = Persistent Stored Modules CREATE PROCEDURE proc_name(param_decls) local_decls proc_body; CREATE FUNCTION func_name(param_decls) RETURNS return_type local_decls func_body; CALL proc_name(params); Inside procedure body: SET variable = CALL func_name(params);

6 SQL/PSM example CREATE FUNCTION SetMaxPop(IN newmaxpop FLOAT) RETURNS INT -- Enforce newmaxpop; return # rows modified. BEGIN DECLARE rowsupdated INT DEFAULT 0; DECLARE thispop FLOAT; --A cursor to range over all users: DECLARE usercursor CURSOR FOR SELECT pop FROM User FOR UPDATE; --Set a flag upon not found exception: DECLARE nomorerows INT DEFAULT 0; DECLARE CONTINUE HANDLER FOR NOT FOUND SET nomorerows = 1; (see next slide) RETURN rowsupdated; END

7 SQL/PSM example continued --Fetch the first result row: OPEN usercursor; FETCH FROM usercursor INTO thispop; --Loop over all result rows: WHILE nomorerows <> 1 DO IF thispop > newmaxpop THEN -- Enforce newmaxpop: UPDATE User SET pop = newmaxpop WHERE CURRENT OF usercursor; -- Update count: SET rowsupdated = rowsupdated + 1; END IF; --Fetch the next result row: FETCH FROM usercursor INTO thispop; END WHILE; CLOSE usercursor;

8 Other SQL/PSM features Assignment using scalar query results SELECT INTO Other loop constructs FOR, REPEAT UNTIL, LOOP Flow control GOTO Exceptions SIGNAL, RESIGNAL For more PostgreSQL-specific information, look for PL/pgSQL in PostgreSQL documentation Link available from course website (under Help: PostgreSQL Tips)

9 Interfacing SQL with another language API approach SQL commands are sent to the DBMS at runtime Examples: Python DB API, JDBC, ODBC (C/C ++ /VB) These API s are all based on the SQL/CLI (Call-Level Interface) standard Embedded SQL approach SQL commands are embedded in application code A precompilerchecks these commands at compile-time and converts them into DBMS-specific API calls Examples: embedded SQL for C/C++, SQLJ (for Java)

10 Example API: Python psycopg2 import psycopg2 conn = psycopg2.connect(dbname='beers') cur = conn.cursor() # list all drinkers: cur.execute('select * FROM Drinker') for drinker, address in cur: print drinker + ' lives at ' + address #print menu for bars whose name contains a : cur.execute('select * FROM Serves WHERE bar LIKE %s', ('%a%',)) for bar, beer, price in cur: print bar + ' serves ' + beer\ + ' at ${:,.2f}'.format(price) cur.close() conn.close() You can iterate over cur one tuple at a time Placeholder for query parameter Tuple of parameter values, one for each %s (note that the trailing, is needed when the tuple contains only one value)

11 More psycopg2examples # commit each change immediately need to set this option just once at the start of the session conn.set_session(autocommit=true) #... bar = raw_input('enter the bar to update: ').strip() beer = raw_input('enter the beer to update: ').strip() price = float(raw_input('enter the new price: ')) try: cur.execute(''' UPDATE Serves SET price = %s WHERE bar = %s AND beer = %s''', (price, bar, beer)) if cur.rowcount!= 1: print '{} row(s) updated: correct bar/beer?'\.format(cur.rowcount) except Exception as e: print e # of tuples modified Exceptions can be thrown (e.g., if positive-price constraint is violated)

12 Prepared statements: motivation while True: # Input bar, beer, price cur.execute(''' UPDATE Serves SET price = %s WHERE bar = %s AND beer = %s''', (price, bar, beer)) #Check result... Every time we send an SQL string to the DBMS, it must perform parsing, semantic analysis, optimization, compilation, and finally execution A typical application issues many queries with a small number of patterns (with different parameter values) Can we reduce this overhead?

13 Prepared statements: example See /opt/dbcourse/examples/psycopg2/ on your VM for a complete code example cur.execute(''' #Prepare once (in SQL). PREPARE update_price AS # Name the prepared plan, UPDATE Serves SET price = $1 #and note the $1, $2, notation for WHERE bar = $2 AND beer = $3''') #parameter placeholders. while True: # Input bar, beer, price cur.execute('execute update_price(%s, %s, %s)',\ # Execute many times. (price, bar, beer)) # Note the switch back to %s for parameter placeholders. #Check result... The DBMS performs parsing, semantic analysis, optimization, and compilation only once, when it prepares the statement At execution time, the DBMS only needs to check parameter types and validate the compiled plan Most other API s have better support for prepared statements than psycopg2 E.g., they would provide a cur.prepare() method

14 Exploits of a mom http://xkcd.com/327/ The school probably had something like: cur.execute("select * FROM Students " + \ "WHERE (name = '" + name + "')") where name is a string input by user Called an SQL injection attack

15 Guarding against SQL injection Escape certain characters in a user input string, to ensure that it remains a single string E.g., ', which would terminate a string in SQL, must be replaced by ''(two single quotes in a row) within the input string Luckily, most API s provide ways to sanitize input automatically (if you use them properly) E.g., pass parameter values in psycopg2 through %s s

16 Augmenting SQL vs. API Pros of augmenting SQL: Cons of augmenting SQL:

17 A brief look at other approaches Embed SQL in general-purpose programming languages E.g.: embedded SQL Extend general-purpose programming languages with SQL-like constructs E.g.: LINQ (Language Integrated Query for.net)

18 Embedded SQL Embed SQL inside code written in a generalpurpose language Special keywords mark code sections containing SQL or variables holding data to be passed to/from SQL A pre-compiler parses the program and automatically convert the special sections to code with appropriate API calls Pros: more compile-time checking, and potentially more optimization opportunities Cons: DBMS-specific: Different pre-compilers for different DBMS vendors Program executable not portable across DBMS s Difficult for a program to talk to DBMS s from different vendors

19 Embedded SQL example (in C) EXEC SQL BEGIN DECLARE SECTION; int thisuid; float thispop; EXEC SQL END DECLARE SECTION; EXEC SQL DECLARE ABCMember CURSOR FOR SELECT uid, pop FROM User WHERE uid IN (SELECT uid FROM Member WHERE gid = 'abc') FOR UPDATE; EXEC SQL OPEN ABCMember; EXEC SQL WHENEVER NOT FOUND DO break; while (1) { } EXEC SQL FETCH ABCMember INTO :thisuid, :thispop; printf("uid %d: current pop is %f\n", thisuid, thispop); printf("enter new popularity: "); scanf("%f", &thispop); EXEC SQL UPDATE User SET pop = :thispop WHERE CURRENT OF ABCMember; EXEC SQL CLOSE ABCMember; Declare variables to be shared between the application and DBMS Specify a handler for NOT FOUND exception

20 Adding SQL to a language Example: LINQ (Language Integrated Query) for Microsoft.NET languages (e.g., C#) int somevalue = 5; var results = from c in somecollection let x = somevalue * 2 where c.someproperty < x select new {c.someproperty, c.otherproperty}; foreach (var result in results) { Console.WriteLine(result); } Automatic data mapping and query translation But syntax may vary for different host languages