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



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

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

Jeffrey D. Ullman Anfang von: CS145 - Herbst Stanford University Online unter: Folien mit weißem Hintergrund wurden hinzugefügt!

Real SQL Programming 1

Constraints, Triggers, and Database Programming Information Systems Q2, Ira Assent

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

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

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

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.

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

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

Programming Database lectures for mathema

SQL: Programming. Introduction to Databases CompSci 316 Fall 2014

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

Database Access from a Programming Language:

Relational Algebra. Basic Operations Algebra of Bags

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

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

More SQL: Assertions, Views, and Programming Techniques

SQL and Java. Database Systems Lecture 19 Natasha Alechina

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

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

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

Developing an ODBC C++ Client with MySQL Database

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

Moving from CS 61A Scheme to CS 61B Java

Hypercosm. Studio.

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

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

Part 16: Application. Programming I. 16. Application Programming I (Embedded SQL, ODBC, JDBC) References:

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

N3458: Simple Database Integration in C++11

Lab 9 Access PreLab Copy the prelab folder, Lab09 PreLab9_Access_intro

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

Database Design and Programming

Object-Oriented Query Languages: Object Query Language (OQL)

Embedded SQL programming

IBM soliddb IBM soliddb Universal Cache Version 6.3. Programmer Guide SC

ODBC Sample Application for Tandem NonStop SQL/MX

Database Access via Programming Languages

SQL and programming languages

Oracle Database: SQL and PL/SQL Fundamentals NEW

Syntax Check of Embedded SQL in C++ with Proto

Transactions, Views, Indexes. Controlling Concurrent Behavior Virtual and Materialized Views Speeding Accesses to Data

DATABASDESIGN FÖR INGENJÖRER - 1DL124

Oracle Database: SQL and PL/SQL Fundamentals

Using SQL Server Management Studio

A Brief Introduction to MySQL

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

Vim, Emacs, and JUnit Testing. Audience: Students in CS 331 Written by: Kathleen Lockhart, CS Tutor

Creating Customized Oracle Forms

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

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

Using ORACLE in the CSLab

1 Stored Procedures in PL/SQL 2 PL/SQL. 2.1 Variables. 2.2 PL/SQL Program Blocks

Raima Database Manager 11.0

CS/CE 2336 Computer Science II

5.1 Database Schema Schema Generation in SQL

1 SQL Data Types and Schemas

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

Database System Concepts

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies)

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

Intro to Embedded SQL Programming for ILE RPG Developers

Programming Languages CIS 443

Relational Database: Additional Operations on Relations; SQL

Exercise 1: Python Language Basics

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

To Java SE 8, and Beyond (Plan B)

Java 7 Recipes. Freddy Guime. vk» (,\['«** g!p#« Carl Dea. Josh Juneau. John O'Conner

12 Embedding SQL in Programming languages

PL / SQL Basics. Chapter 3

Instant SQL Programming

12 Embedding SQL in Programming languages

Self-test Database application programming with JDBC

The release notes provide details of enhancements and features in Cloudera ODBC Driver for Impala , as well as the version history.

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

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

How I hacked PacketStorm ( )

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

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

On-Line Application Processing. Warehousing Data Cubes Data Mining

N3612: Desiderata of a C++11 Database Interface

MyOra 3.0. User Guide. SQL Tool for Oracle. Jayam Systems, LLC

Technical Standard. Data Management: SQL Call Level Interface (CLI)

Seminar Datenbanksysteme

Introduction. Syntax Statements. Colon : Line Continuation _ Conditions. If Then Else End If 1. block form syntax 2. One-Line syntax. Do...

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

LogLogic General Database Collector for Microsoft SQL Server Log Configuration Guide

Exercise 4 Learning Python language fundamentals

14 Triggers / Embedded SQL

Visual Basic. murach's TRAINING & REFERENCE

Persistent Stored Modules (Stored Procedures) : PSM

Darshan Institute of Engineering & Technology PL_SQL

Applets, RMI, JDBC Exam Review

Making Standard ML a Practical Database Programming Language

Writing MySQL Scripts With Python's DB-API Interface

There are five fields or columns, with names and types as shown above.

Transcription:

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

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. Programs in a conventional language like C are written to access a database by calls to SQL statements. 2

Host Languages Any conventional language can be a host language, that is, a language in which SQL calls are embedded. The use of a host/sql combination allows us to do anything computable, yet still get the very-high-level SQL interface to the database. 3

Connecting SQL to the Host Language 1. Embedded SQL is a standard for combining SQL with seven languages. 2. CLI (Call-Level Interface ) is a different approach to connecting C to an SQL database. 3. JDBC (Java Database Connectivity ) is a way to connect Java with an SQL database. 4

Embedded SQL Key idea: Use a preprocessor to turn SQL statements into procedure calls that fit with the host-language code surrounding. All embedded SQL statements begin with EXEC SQL, so the preprocessor can find them easily. 5

Shared Variables Always needed To connect SQL and the host-language program, the two parts must share some variables. Declarations of shared variables are bracketed by: EXEC SQL BEGIN DECLARE SECTION; <host-language declarations> EXEC SQL END DECLARE SECTION; 6

Use of Shared Variables In SQL, the shared variables must be preceded by a colon. They may be used as constants provided by the host-language program. They may get values from SQL statements and pass those values to the hostlanguage program. In the host language, shared variables behave like any other variable. 7

Example: Looking Up Prices We ll use C with embedded SQL to sketch the important parts of a function that obtains a beer and a bar, and looks up the price of that beer at that bar. Assumes database has our usual Sells(bar, beer, price) relation. 8

Example: C Plus SQL EXEC SQL BEGIN DECLARE SECTION; char thebar[21], thebeer[21]; float theprice; EXEC SQL END DECLARE SECTION; /* obtain values for thebar and thebeer */ EXEC SQL SELECT price INTO :theprice FROM Sells WHERE bar = :thebar AND beer = :thebeer; /* do something with theprice */ Note 21-char arrays needed for 20 chars + endmarker SELECT-INTO just like PSM9

Embedded Queries Embedded SQL has the same limitations as PSM regarding queries: You may use SELECT-INTO for a query guaranteed to produce a single tuple. Otherwise, you have to use a cursor. Small syntactic differences between PSM and Embedded SQL cursors, but the key ideas are identical. 10

Cursor Statements Declare a cursor c with: EXEC SQL DECLARE c CURSOR FOR <query>; Open and close cursor c with: EXEC SQL OPEN CURSOR c; EXEC SQL CLOSE CURSOR c; Fetch from c by: EXEC SQL FETCH c INTO <variable(s)>; Macro NOT FOUND is true if and only if the FETCH fails to find a tuple. 11

Example --- (1) Let s write C + SQL to print Joe s menu --- the list of beer-price pairs that we find in Sells(bar, beer, price) with bar = Joe s Bar. A cursor will visit each Sells tuple that has bar = Joe s Bar. 12

Example --- (2: Declarations) EXEC SQL BEGIN DECLARE SECTION; char thebeer[21]; float theprice; EXEC SQL END DECLARE SECTION; EXEC SQL DECLARE c CURSOR FOR SELECT beer, price FROM Sells WHERE bar = Joe s Bar ; The cursor declaration goes outside the declare-section 13

Example --- (3: Executable) EXEC SQL OPEN CURSOR c; The C style while(1) { of breaking loops EXEC SQL FETCH c INTO :thebeer, :theprice; if (NOT FOUND) break; /* format and print thebeer and theprice */ } EXEC SQL CLOSE CURSOR c; 14

Need for Dynamic SQL Most applications use specific queries and modification statements to interact with the database. The DBMS compiles EXEC SQL statements into specific procedure calls and produces an ordinary host-language program that uses a library. What about sqlplus, which doesn t know what it needs to do until it runs? 15

Dynamic SQL Preparing a query: EXEC SQL PREPARE <query-name> FROM <text of the query>; Executing a query: EXEC SQL EXECUTE <query-name>; Prepare = optimize query. Prepare once, execute many times. 16

Example: A Generic Interface EXEC SQL BEGIN DECLARE SECTION; char query[max_length]; EXEC SQL END DECLARE SECTION; while(1) { /* issue SQL> prompt */ /* read user s query into array query */ EXEC SQL PREPARE q FROM :query; EXEC SQL EXECUTE q; } q is an SQL variable representing the optimized form of whatever statement is typed into :query 17

Execute-Immediate If we are only going to execute the query once, we can combine the PREPARE and EXECUTE steps into one. Use: EXEC SQL EXECUTE IMMEDIATE <text>; 18

Example: Generic Interface Again EXEC SQL BEGIN DECLARE SECTION; char query[max_length]; EXEC SQL END DECLARE SECTION; while(1) { /* issue SQL> prompt */ /* read user s query into array query */ EXEC SQL EXECUTE IMMEDIATE :query; } 19

SQL/CLI Instead of using a preprocessor, we can use a library of functions and call them as part of an ordinary C program. The library for C is called SQL/CLI = Call- Level Interface. Embedded SQL s preprocessor will translate the EXEC SQL statements into CLI or similar calls, anyway. 20

Data Structures C connects to the database by structs of the following types: 1. Environments : represent the DBMS installation. 2. Connections : logins to the database. 3. Statements : SQL statements to be passed to a connection. 4. Descriptions : records about tuples from a query or parameters of a statement. 21

Environments, Connections, and Statements Function SQLAllocHandle(T,I,O) is used to create these structs, which are called environment, connection, and statement handles. T = type, e.g., SQL_HANDLE_STMT. I = input handle = struct at next higher level (statement < connection < environment). O = (address of) output handle. 22

Example: SQLAllocHandle SQLAllocHandle(SQL_HANDLE_STMT, mycon, &mystat); mycon is a previously created connection handle. mystat is the name of the statement handle that will be created. 23

Preparing and Executing SQLPrepare(H, S, L) causes the string S, of length L, to be interpreted as an SQL statement and optimized; the executable statement is placed in statement handle H. SQLExecute(H) causes the SQL statement represented by statement handle H to be executed. 24

Example: Prepare and Execute SQLPrepare(myStat, SELECT beer, price FROM Sells WHERE bar = Joe s Bar, SQL_NTS); SQLExecute(myStat); This constant says the second argument is a null-terminated string ; i.e., figure out the length by counting characters. 25

Dynamic Execution If we will execute a statement S only once, we can combine PREPARE and EXECUTE with: SQLExecuteDirect(H,S,L); As before, H is a statement handle and L is the length of string S. 26

Fetching Tuples When the SQL statement executed is a query, we need to fetch the tuples of the result. That is, a cursor is implied by the fact we executed a query, and need not be declared. SQLFetch(H) gets the next tuple from the result of the statement with handle H. 27

Accessing Query Results When we fetch a tuple, we need to put the components somewhere. Thus, each component is bound to a variable by the function SQLBindCol. This function has 6 arguments, of which we shall show only 1, 2, and 4: 1 = handle of the query statement. 2 = column number. 4 = address of the variable. 28

Example: Binding Suppose we have just done SQLExecute(myStat), where mystat is the handle for query SELECT beer, price FROM Sells WHERE bar = Joe s Bar Bind the result to thebeer and theprice: SQLBindCol(myStat, 1,, &thebeer,, ); SQLBindCol(myStat, 2,, &theprice,, ); 29

Example: Fetching Now, we can fetch all the tuples of the answer by: while ( SQLFetch(myStat)!= SQL_NO_DATA) { /* do something with thebeer and } theprice */ CLI macro representing SQLSTATE = 02000 = failed to find a tuple. 30

JDBC Java Database Connectivity (JDBC) is a library similar to SQL/CLI, but with Java as the host language. JDBC/CLI differences are often related to the object-oriented style of Java, but there are other differences. 31

Environments, Connections, and Statements The same progression from environments to connections to statements that we saw in CLI appears in JDBC. A connection object is obtained from the environment in a somewhat implementation-dependent way. We ll start by assuming we have mycon, a connection object. 32

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

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 = Joe s Bar ); Java trick: + concatenates strings. createstatement with no argument returns a Statement; with one argument it returns a PreparedStatement. 34

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

Example: Update stat1 is a Statement. We can use it to insert a tuple as: stat1.executeupdate( INSERT INTO Sells + VALUES( Brass Rail, Bud, 3.00) ); 36

Example: Query stat2 is a PreparedStatement holding the query SELECT beer, price FROM Sells WHERE bar = Joe s Bar. executequery returns an object of class ResultSet --- we ll examine it later. The query: ResultSet Menu = stat2.executequery(); 37

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. 38

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. 39

Example: Accessing Components Menu is the ResultSet for the query SELECT beer, price FROM Sells WHERE bar = Joe s Bar. Access the beer and price from each tuple by: while ( Menu.Next() ) { thebeer = Menu.getString(1); theprice = Menu.getFloat(2); /* do something with thebeer and theprice */ } 40