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

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

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

CS346: Database Programming.

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

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

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

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

Database Access from a Programming Language:

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

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

Real SQL Programming 1

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

JDBC (Java / SQL Programming) CS 377: Database Systems

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

SQL: Programming. Introduction to Databases CompSci 316 Fall 2014

SQL and Java. Database Systems Lecture 19 Natasha Alechina

CHAPTER 3. Relational Database Management System: Oracle. 3.1 COMPANY Database

Programming Database lectures for mathema

More SQL: Assertions, Views, and Programming Techniques

LSINF1124 Projet de programmation

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

The JAVA Way: JDBC and SQLJ

How I hacked PacketStorm ( )

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

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

Database System Concepts

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

JDBC. It is connected by the Native Module of dependent form of h/w like.dll or.so. ex) OCI driver for local connection to Oracle

Microsoft SQL Server Features that can be used with the IBM i

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

Security Module: SQL Injection

CS/CE 2336 Computer Science II

1 SQL Data Types and Schemas

CS2506 Operating Systems II Lab 8, 8 th Tue/03 /2011 Java API

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

Database programming made easier Master thesis of Roland Balk

The C Programming Language course syllabus associate level

12 Embedding SQL in Programming languages

A Brief Introduction to MySQL

12 Embedding SQL in Programming languages

PostgreSQL Functions By Example

Services. Relational. Databases & JDBC. Today. Relational. Databases SQL JDBC. Next Time. Services. Relational. Databases & JDBC. Today.

1. What is SQL Injection?

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

Working With Derby. Version 10.2 Derby Document build: December 11, 2006, 7:06:09 AM (PST)

Using Netbeans and the Derby Database for Projects Contents

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

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

VHDL Test Bench Tutorial

Performance Tuning for the JDBC TM API

Comparing the Effectiveness of Penetration Testing and Static Code Analysis

FileMaker 14. ODBC and JDBC Guide

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

Using JML to protect Java code against SQL injection. Johan Janssen June 26, 2007

CHAPTER 5 INTELLIGENT TECHNIQUES TO PREVENT SQL INJECTION ATTACKS

SQL Injection. Slides thanks to Prof. Shmatikov at UT Austin

Self-test Database application programming with JDBC

Writing MySQL Scripts With Python's DB-API Interface

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

Lab Experience 17. Programming Language Translation

Seminar Datenbanksysteme

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Sources: On the Web: Slides will be available on:

Accesssing External Databases From ILE RPG (with help from Java)

CS 161 Computer Security

MapReduce. MapReduce and SQL Injections. CS 3200 Final Lecture. Introduction. MapReduce. Programming Model. Example

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

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Introduction to Data Structures

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

Database Access via Programming Languages

Maintaining Stored Procedures in Database Application

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

TABLE OF CONTENTS...2 INTRODUCTION...3 APPLETS AND APPLICATIONS...3 JAVABEANS...4 EXCEPTION HANDLING...5 JAVA DATABASE CONNECTIVITY (JDBC)...

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

SQL and programming languages

Writing Scripts with PHP s PEAR DB Module

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

CSC 370 Database Systems Summer 2004 Assignment No. 2

Using DOTS as Apache Derby System Test

Introduction to Triggers using SQL

DEVELOPING MULTITHREADED DATABASE APPLICATION USING JAVA TOOLS AND ORACLE DATABASE MANAGEMENT SYSTEM IN INTRANET ENVIRONMENT

Java Server Pages and Java Beans

Agenda. SQL Injection Impact in the Real World Attack Scenario (1) CHAPTER 8 SQL Injection

14 Triggers / Embedded SQL

Supplement IV.D: Tutorial for MS Access. For Introduction to Java Programming By Y. Daniel Liang

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

J a v a Quiz (Unit 3, Test 0 Practice)

FileMaker 13. ODBC and JDBC Guide

Understanding Sql Injection

Applets, RMI, JDBC Exam Review

COMP 110 Prasun Dewan 1

Advanced Tornado TWENTYONE Advanced Tornado Accessing MySQL from Python LAB

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

An Eclipse Plug-In for Visualizing Java Code Dependencies on Relational Databases

database abstraction layer database abstraction layers in PHP Lukas Smith BackendMedia

Transcription:

Embedded SQL csc343, Introduction to Databases Diane Horton with examples from Ullman and Widom Winter 2017

Problems with using interactive SQL Standard SQL is not Turing-complete. E.g., Two profs are colleagues if they ve co-taught a course or share a colleague. We can t write a query to find all colleagues of a given professor because we have no loops or recursion. You can t control the format of its output. And most users shouldn t be writing SQL queries! You want to run queries that are based on user input, not have users writing actual queries. 2

SQL + a conventional language If we can combine SQL with code in a conventional language, we can solve these problems. But we have another problem: SQL is based on relations, and conventional languages have no such type. It is solved by feeding tuples from SQL to the other language one at a time, and feeding each attribute value into a particular variable. 3

Approaches Three approaches for combining SQL and a general-purpose language: Stored Procedures Statement-level Interface Call-level interface 4

Three Approaches

1. Stored Procedures The SQL standard includes a language for defining stored procedures, which can have parameters and a return value, use local variables, ifs, loops, etc., execute SQL queries. Stored procedures can be used in these ways: called from the interpreter, called from SQL queries, called from another stored procedure, be the action that a trigger performs. 6

Example (just to give you an idea) A boolean function BandW(y INT, s CHAR(15)) that returns true iff movie studio s produced no movies in year y, or produced at least one comedy. (Yes, that s an odd name for this function.) Reference: Ullman and Widom textbook, chapter 9 7

Reference: textbook figure 9.1.3 CREATE FUNCTION BandW(y INT, s CHAR(15)) RETURNS BOOLEAN IF NOT EXISTS (SELECT * FROM Movies WHERE year = y AND studioname = s) THEN RETURN TRUE; ELSIF 1 <= (SELECT COUNT(*) FROM Movies WHERE year = y AND studioname = s AND genre = comedy ) THEN RETURN TRUE; ELSE RETURN FALSE; END IF; 8

Calling it Now we can say things like this: SELECT StudioName FROM Studios WHERE BandW(2010, StudioName); 9

Not very standard The language is called SQL/PSM (Persistent Stored Modules). It came into the SQL standard in SQL3, 1999. Reference: textbook, section 9.4 By then, commercial DBMSs had defined their own proprietary languages for stored procedures They have generally stuck to them. PostgreSQL has defined PL/pgSQL. It supports some, but not all, of SQL/PSM. Reference: Chapter 39 of the PostgreSQL documentation. 10

2. Statement-level interface (SLI) Embed SQL statements into code in a conventional language like C or Java. Use a preprocessor to replace the SQL with calls written in the host language to functions defined in an SQL library. Special syntax indicates which bits of code the preprocessor needs to convert. 11

Example, in C (just to give you an idea) Reference: textbook example 9.7 void printnetworth() { EXEC SQL BEGIN DECLARE SECTION; char studioname[50]; int presnetworth; char SQLSTATE[6]; // Status of most recent SQL stmt EXEC SQL END DECLARE SECTION; /* OMITTED: Get value for studioname from the user. */ EXEC SQL SELECT networth INTO :presnetworth FROM Studio, MovieExec WHERE Studio.name = :studioname; /* OMITTED: Report back to the user */ } 12

Big picture (figure 9.5) User SLI Host language + Embedded SQL CLI Preprocessor Host language + Function calls Host-language compiler SQL library Object-code program 13

3. Call-level interface (CLI) Instead of using a pre-processor to replace embedded SQL with calls to library functions, write those calls yourself. Eliminates need to preprocess. Each language has its own set of library functions for this. for C, it s called SQL/CLI for Java, it s called JDBC for PHP, it s called PEAR DB We ll look at just one: JDBC. 14

JDBC

JDBC Example (see section 9.6) Do this once in your program: /* Get ready to execute queries. */ import java.sql.*; /* A static method of the Class class. It loads the specified driver */ Class.forName( org.postgresql.jdbc.driver ); Connection conn = DriverManager.getConnection( jdbc:postgresql://localhost:5432/csc343h-dianeh, dianeh, ); /* Continued... */ 16

The arguments to getconnection jdbc:postgresql We ll use this, but it could be, e.g., jdbc:mysql localhost:5432 You must use exactly this for the CS Teaching Labs. csc343h-dianeh and dianeh Substitute your userid on the CS Teaching Labs. Password (unrelated to your password). Literally use the empty string. 17

Do this once per query in your program: /* Execute a query and iterate through the resulting tuples. */ PreparedStatement execstat = conn.preparestatement( SELECT networth FROM MovieExec ); ResultSet worths = execstat.executequery(); while (worths.next()) { } int worth = worths.getint(1); /* If the tuple also had a float and another int attribute, you d get them by calling worths.getfloat(2) and worths.getint(3). Or you can look up values by attribute name. Example: worths.getint(networth) */ /* OMITTED: Process this net worth */ 18

The Java details For full details on the Java classes and methods used, see the Java API documentation: https://docs.oracle.com/javase/8/docs/api/java/sql/ package-summary.html 19

Exceptions can occur Any of these calls can generate an exception. Therefore, they should be inside try/catch blocks. try { /* OMITTED: JDBC code */ } catch (SQLException ex) { /* OMITTED: Handle the exception */ } The class SQLException has methods to return the SQLSTATE, etc. 20

What is preparation? Preparing a statement includes: parsing the SQL compiling optimizing The resulting PreparedStatement can be executed any number of times without having to repeat these steps. 21

If the query isn t known until run time You may need input and computation to determine exactly what the query should be. In that case: Hard-code in the parts you know. Use the character? as a placeholder for the values you don t know. (Don t put it in quotes!) This is enough to allow a PreparedStatement to be constructed. Once you know values for the placeholders, use methods setstring, setint, etc. to fill in those values. 22

Example (figure 9.22) PreparedStatement studiostat = conn.preparedstatement( INSERT INTO Studio(name, address) VALUES(?,?) ); /* OMITTED: Get values for studioname and studioaddr */ studiostat.setstring(1, studioname); studiostat.setstring(2, studioaddr); studiostat.executeupdate(); 23

Why not just build the query in a string? We constructed an incomplete preparedstatement and filled in the missing values using method calls. Instead, we could just build up the query in an ordinary string at run time, and ask to execute that. There are classes and methods that will do this in JDBC. 24

Example that builds the query in a string We can just use a Statement, and give it a String to execute. // stat cannot be compiled & optimized (yet). Statement stat = conn.createstatement(); String query = SELECT networth FROM MovieExec WHERE execname like %Spielberg% ; // executequery can now compile and optimize, and run // the query. ResultSet worths = stat.executequery(query); 25

What could possibly go wrong? 26

Example: Some vulnerable code Suppose we want the user to provide the string to compare to You can do this rather than hard-coding Spielberg into the query: Statement stat = conn.createstatement(); String who = /* get a string from the user */ String query = SELECT networth FROM MovieExec WHERE execname like % + who + % ; ResultSet worths = stat.executequery(query); 27

A gentle user does no harm If a user enters Milch, the SQL code we execute is this: SELECT networth FROM MovieExec WHERE execname like %Milch% ; Nothing bad happens. 28

An injection can exploit the vulnerability What could a malicious user enter? SELECT networth FROM MovieExec WHERE execname like %?????????????% ; 29

Always use a PreparedStatement This was an example of an injection. The simple approach of giving a String to a Statement is vulnerable to injections. Moral of the story: Always use a PreparedStatement instead. 30

Queries vs updates in JDBC The previous examples used executequery. This method is only for pure queries. For SQL statements that change the database (insert, delete or modify tuples, or change the schema), use the analogous method executeupdate. 31