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



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

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

Real SQL Programming 1

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

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

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

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:

SQL: Programming. Introduction to Databases CompSci 316 Fall 2014

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

Embedded SQL programming

Programming Database lectures for mathema

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

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

Database Access via Programming Languages

More SQL: Assertions, Views, and Programming Techniques

CS346: Database Programming.

12 Embedding SQL in Programming languages

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

12 Embedding SQL in Programming languages

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

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

SQL and programming languages

Embedding SQL in High Level Language Programs

IBM Power Systems Software. The ABCs of Coding High Performance SQL Apps DB2 for IBM i. Presented by Jarek Miszczyk IBM Rochester, ISV Enablement

ASP.NET Programming with C# and SQL Server

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

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

Developing an ODBC C++ Client with MySQL Database

Using SQL in RPG Programs: An Introduction

ODBC Client Driver Help Kepware, Inc.

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

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

SQLITE C/C++ TUTORIAL

/* Errors from here on will cause the program to clean up */

Database DB2 Universal Database for iseries Embedded SQL programming

N3458: Simple Database Integration in C++11

DB2. Getting Started with Database Application Development. DB2 Version 9 SC

A Brief Introduction to MySQL

1 SQL Data Types and Schemas

Lab 9 Access PreLab Copy the prelab folder, Lab09 PreLab9_Access_intro

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

Database Access from a Programming Language:

DB2 Application Development and Migration Tools

DB2 Application Development overview

Chapter 4 Accessing Data

14 Triggers / Embedded SQL

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

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

FileMaker 11. ODBC and JDBC Guide

Database Application Developer Tools Using Static Analysis and Dynamic Profiling

Chapter 13: Program Development and Programming Languages

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

Using Microsoft SQL Server A Brief Help Sheet for CMPT 354

Connect to an Oracle Database from within Visual Basic 6 (Part 1)

Architecting the Future of Big Data

DB2 Connect for NT and the Microsoft Windows NT Load Balancing Service

Intro to Embedded SQL Programming for ILE RPG Developers

IMS Users Group. The Right Change SQL-Based Middleware. Mike McKee CONNX Solutions.

ODBC Sample Application for Tandem NonStop SQL/MX

High-Performance Oracle: Proven Methods for Achieving Optimum Performance and Availability

Microsoft Access is an outstanding environment for both database users and professional. Introduction to Microsoft Access and Programming SESSION

Beginning C# 5.0. Databases. Vidya Vrat Agarwal. Second Edition

Using ORACLE in the CSLab

The Data Access Handbook

OBJECTSTUDIO. Database User's Guide P

Architecting the Future of Big Data

Architecting the Future of Big Data

Getting Started with STATISTICA Enterprise Programming

Application Development Guide: Programming Server Applications

.NET Overview. Andreas Schabus Academic Relations Microsoft Österreich GmbH

The programming language C. sws1 1

Using SQL Server Management Studio

Visual COBOL ASP.NET Shopping Cart Demonstration

ERserver. Embedded SQL programming. iseries. Version 5 Release 3

Darshan Institute of Engineering & Technology PL_SQL

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

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

ODBC Chapter,First Edition

Introducing Micro Focus Net Express to Develop and Extend COBOL Applications within.net White Paper

Acknowledgments. About the Author

BarTender Integration Methods. Integrating BarTender s Printing and Design Functionality with Your Custom Application WHITE PAPER

Application Development Guide: Building and Running Applications

DATABASE SYSTEM CONCEPTS AND ARCHITECTURE CHAPTER 2

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

1 File Processing Systems

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

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

Database Toolkit: Portable and Cost Effective Software

SQL. Agenda. Where you want to go Today for database access. What is SQL

Title. Syntax. stata.com. odbc Load, write, or view data from ODBC sources. List ODBC sources to which Stata can connect odbc list

Physical File. Collection or Schema

Progress Embedded SQL-92 Guide and Reference

DATABASDESIGN FÖR INGENJÖRER - 1DL124

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

Crystal Reports. For Visual Studio.NET. Reporting Off ADO.NET Datasets

Making Standard ML a Practical Database Programming Language

BarTender s ActiveX Automation Interface. The World's Leading Software for Label, Barcode, RFID & Card Printing

COMMON All Day Lab 10/16/2007 Hands on VB.net and ASP.Net for iseries Developers

Chapter 13 Computer Programs and Programming Languages. Discovering Computers Your Interactive Guide to the Digital World

Transcription:

SQL and Programming Languages SQL in Programming Languages Read chapter 5 of Atzeni et al. BD: Modelli e Linguaggi di Interrogazione and section 8.4 of Garcia-Molina The user does not want to execute SQL statement She wants to interact with an application targeted to her domain Limited set of choices Simple execution of complex operations Graphical interface: Simple data input Nice data output (presentation) Slides derived from those by Jeffrey D. Ullman 2 Applications They are written in traditional programming languages: C, C++, Java, Fortran, C#, Visual Basic, Cobol Host languages Approaches Embedded SQL Older approach (since the 70s) Call Level Interface (CLI) Most recent SQL/CLI, ODBC, JDBC 3 4

Embedded SQL In the embedded SQL approach the programmer inserts SQL statements directly in the source code of the host programming language A precompiler is used to translate the code so that SQL statements are translated into function/procedure calls of the specific DBMS API From a file containing embedded SQL to a file in the same language containing function calls Concrete Examples In DB2 you can develop embedded SQL applications in the following host programming languages: C, C++, COBOL, FORTRAN, and REXX The DB2 precompiler is invoked with PREP (PRECOMPILE) In Postgres the preprocessor for C is called ECPG 5 6 Shared Variables To connect SQL and the host-language program, the two parts must share some variables. Declarations of shared variables are bracketed by: <host-language declarations> 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 host-language program. In the host language, shared variables behave like any other variable. 7 8

Example: C Plus SQL char thebar[21], thebeer[21]; float theprice; /* obtain values for thebar and thebeer */ EXEC SQL SELECT price INTO :theprice FROM Sells WHERE bar = :thebar AND beer = :thebeer; /* do something with theprice */ Embedded 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. 9 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. 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. 11 12

Example 2 (Declarations) char thebeer[21]; float theprice; EXEC SQL DECLARE c CURSOR FOR SELECT beer, price FROM Sells WHERE bar = Joe s Bar ; Example 3 (Executable) EXEC SQL OPEN CURSOR c; while(1) EXEC SQL FETCH c INTO :thebeer, :theprice; if (NOT FOUND) break; /* format and print thebeer and theprice */ EXEC SQL CLOSE CURSOR c; 13 14 Need for Dynamic SQL Most applications use specific queries and modification statements in their interaction with the database. Thus, we can compile the EXEC SQL statements into specific procedure calls and produce an ordinary host-language program that uses a library. What if the program is something like a generic query interface, that doesn t know what it needs to do until it runs? 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. 15 16

Example: A Generic Interface char query[max_length]; while(1) /* issue SQL> prompt */ /* read user s query into array query */ EXEC SQL PREPARE q FROM :query; EXEC SQL EXECUTE q; 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>; 17 18 Example: Generic Interface Again char query[max_length]; while(1) /* issue SQL> prompt */ /* read user s query into array query */ EXEC SQL EXECUTE IMMEDIATE :query; #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sqlenv.h> #include <sqlutil.h> short id; char name[10]; short dept; double salary; char hostvarstmtdyn[50]; 19 20

int main() int rc = 0; EXEC SQL INCLUDE SQLCA; The SQLCA structure is updated after the execution of each SQL statement. /* connect to the database */ printf("\n Connecting to database..."); SQLCODE is a field of EXEC SQL CONNECT TO "sample"; SQLCA that contains the result of the last operation printf("\nconnect Error: SQLCODE = %d\n,sqlcode); goto connect_reset; else printf("\n Connected to database.\n"); /* execute an SQL statement (a query) using static SQL; copy the single row of result values into host variables*/ EXEC SQL SELECT id, name, dept, salary INTO :id, :name, :dept, :salary FROM staff WHERE id = 310; printf("select Error: SQLCODE = %d\n,sqlcode); else /* print the host variable values to standard output */ printf("\n Executing a static SQL query statement, searching for \n the id value equal to 310\n"); printf("\n ID Name DEPT Salary\n"); printf(" %d\t%s\t%d\t%f\n,id,name,dept.salary); 21 22 strcpy(hostvarstmtdyn, "UPDATE staff SET salary = salary + 1000 WHERE dept =?"); /* execute an SQL statement (an operation) using a host variable and DYNAMIC SQL*/ EXEC SQL PREPARE StmtDyn FROM :hostvarstmtdyn; printf("prepare Error: SQLCODE = %d\n,sqlcode); else EXEC SQL EXECUTE StmtDyn USING :dept; printf("execute Error: SQLCODE = %d\n,sqlcode); /* Read the updated row using STATIC SQL and CURSOR */ EXEC SQL DECLARE poscur1 CURSOR FOR SELECT id, name, dept, salary FROM staff WHERE id = 310; printf("declare Error: SQLCODE = %d\n,sqlcode); EXEC SQL OPEN poscur1; EXEC SQL FETCH poscur1 INTO :id, :name, :dept, :salary ; 23 24

printf("fetch Error: SQLCODE = %d\n,sqlcode); else printf(" Executing an dynamic SQL statement, updating the \n salary value for the id equal to 310\n"); printf("\n ID Name DEPT Salary\n"); printf(" %d\t%s\t%d\t%f\n,id,name,dept.salary); EXEC SQL CLOSE poscur1; /* Commit the transaction */ printf("\n Commit the transaction.\n"); EXEC SQL COMMIT; printf("error: SQLCODE = %d\n,sqlcode); /* Disconnect from the database */ connect_reset : EXEC SQL CONNECT RESET; printf("connection Error: SQLCODE = %d\n,sqlcode); return 0; /* end main */ 25 26 Call Level Interface Sending commands to DBMS by means of function calls of an API standard SQL/CLI ( 95 an then part of SQL:1999) ODBC: proprietary (Microsoft) implementation of SQL/CLI OLE DB: high level API ADO: higher level API JDBC: CLI for Java SQL/CLI SQL/CLI is the library for C ODBC differs from SQL/CLI in minor details 27 28

Data Structures Environments, Connections, and Statements 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 : records that hold SQL statements to be passed to a connection. 4.Descriptions : records about tuples from a query or parameters of a statement. 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. 29 30 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. Preparing and Executing SQLPrepare(H, S, L) causes the string S, of length L, to be interpreted as an SQL statement, optimized, and the executable statement is placed in statement handle H. SQLExecute(H) causes the SQL statement represented by statement handle H to be executed. 31 32

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. 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. 33 34 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. 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. 35 36

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,, ); 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. 37 38 OLE DB ODBC is complicated, so Microsoft proposed OLE DB and ADO OLE DB: is a library that provides applications with uniform access to data stored in diverse information sources Not only relational OLE DB is based on the Microsoft object model: Component Object Model (COM) ADO and ADO.NET ADO: Activex Data Object High level interface for OLE DB ADO.NET: ADO for the.net framework ADO.NET is independent from OLE DB: there does not exist OLE DB.NET 39 40

.NET Framework The.NET Framework is Microsoft's replacement for COM technology. You can code.net applications in over forty different programming languages. The most popular languages for.net development are C# and Visual Basic.NET. The.NET Framework class library provides the building blocks with which you build.net applications. This class library is language agnostic and provides interfaces to operating system and application services..net Framework.NET applications (regardless of language) compile into Intermediate Language (IL), a type of bytecode. The Common Language Runtime (CLR) is the heart of the.net Framework, compiling the IL code on the fly, and then running it. In running the compiled IL code, the CLR activates objects, verifies their security clearance, allocates their memory, executes them, and cleans up their memory once execution is finished. 41 42