Bengkel 1 Guide
-
Upload
muhammad-saifullah -
Category
Documents
-
view
217 -
download
0
Transcript of Bengkel 1 Guide
-
8/13/2019 Bengkel 1 Guide
1/38
TABLE OF CONTENTS
Chapter 1 Introduction to Embedded SQL........................................................................................ 3
1.1 Objectives................................................................................................................................ 3
1.2 Introduction ............................................................................................................................ 31.2.1 Embedded SQL statements.............................................................................................. 3
1.2.2 PRO*C.............................................................................................................................. 3
1.2.3 Steps in executing PRO*C program.................................................................................. 4
1.2.4 List of embedded SQL statements supported by Pro*C................................................... 5
Chapter 2 Configuring Visual Studio 2008 and Pro*c........................................................................ 7
2.1 Objectives................................................................................................................................ 7
2.2 prerequisites ........................................................................................................................... 7
2.3 Configuration steps ................................................................................................................. 7
2.3.1 Specifying the Location of the Pro*C/C++ Executable..................................................... 7
2.3.2 Specifying the Location of the Pro*C/C++ Header Files.................................................... 9
2.3.3 Specifying the Location of the Pro*C/C++ Library folder................................................ 10
2.3.4 Setting Custom Build for .pc extension.......................................................................... 12
2.3.5 Setting the Visual Studio to recognize .pc as C/C++ code............................................... 15
2.3.6 Connect to Oracle database........................................................................................... 16
Chapter 3 Introduction to Embedded SQL Programming............................................................... 21
3.1 Objectives.............................................................................................................................. 21
3.2 Introduction .......................................................................................................................... 21
3.2.1 Embedded SQL syntax.................................................................................................... 21
3.2.2 Host Variables................................................................................................................ 21
3.2.3 Connect to database...................................................................................................... 22
3.2.4 Using SELECT statement................................................................................................. 22
3.2.5 Using INSERT Statements............................................................................................... 23
3.2.6 Error Handling using WHENEVER statement.................................................................. 23
3.2.7 WHENEVER statement - Actions.................................................................................... 24
3.3 Sample Program Revisited..................................................................................................... 25
Chapter 4 Creating a sample menu driven console database-application...................................... 27
4.1 Objectives.............................................................................................................................. 27
-
8/13/2019 Bengkel 1 Guide
2/38
4.2 Database Table Creation ....................................................................................................... 27
4.3 Program Development.......................................................................................................... 28
4.4 Exercise ................................................................................................................................. 38
-
8/13/2019 Bengkel 1 Guide
3/38
CHAPTER 1 INTRODUCTION TO EMBEDDED SQL
1.1 OBJECTIVES
By the end of this chapter, students should be able to:
Understand the term embedded SQL and Pre-compiler Understand how a Pro*C program work
1.2 INTRODUCTION
1.2.1 EMBEDDED SQLSTATEMENTS
The term embedded SQL refers to SQL statements placed within an application program.
As it houses the SQL statements, the application program is called a host program and the
language which it is written is called host language.
Oracles embedded SQL environment is called Pro*C
There are two types of Embedded SQL statements available in Oracle which are:
Executable statements Results in calls to the runtime library SQLLIB
Used to connect to Oracle, to define, query and manipulate Oracle data, to controlaccess to Oracle data, and to process transactions
Directives Do not result in calls to SQLLIB and do not operate on Oracle data Used to declare Oracle objects, communications areas, and SQL variables
1.2.2 PRO*C
PRO*C is a precompiler for C and C++. You can embed SQL statements in your code and thenrun the precompiler (the command isproc) on your source and out comes a new source file
that you can compile as usual.
-
8/13/2019 Bengkel 1 Guide
4/38
Pre-compilers are tools that allow you to embed SQL statements in the High Level Language
source code. Pre-compilers accept SQL statement, translate the SQL statements into runtime
calls, and generate application source code.
Oracle supports pre-compilers for the following High Level Language
C/C++ COBOL Fortran Pascal PL/I Ada
1.2.3 STEPS IN EXECUTING PRO*CPROGRAM
-
8/13/2019 Bengkel 1 Guide
5/38
1.2.4 LIST OF EMBEDDED SQLSTATEMENTS SUPPORTED BY PRO*C
Declarative Statements
EXEC SQL ARRAYLEN To use host arrays with PL/SQL
EXEC SQL BEGIN DECLARE SECTION
EXEC SQL END DECLARE SECTION
To declare host variables
EXEC SQL DECLARE To name Oracle objects
EXEC SQL INCLUDE To copy in files
EXEC SQL TYPE To equivalence datatypes
EXEC SQL VAR To equivalence variables
EXEC SQL WHENEVER To handle runtime errors
Executable Statements
EXEC SQL ALLOCATE To define and control Oracle data
EXEC SQL ALTER
EXEC SQL ANALYZE
EXEC SQL AUDIT
EXEC SQL COMMENT
EXEC SQL CONNECT
EXEC SQL CREATE
EXEC SQL DROP
EXEC SQL GRANT
EXEC SQL NOAUDIT
EXEC SQL RENAME
EXEC SQL REVOKE
EXEC SQL TRUNCATE
EXEC SQL CLOSE
EXEC SQL DELETE To query and manipulate Oracle data
EXEC SQL EXPLAIN PLAN
EXEC SQL FETCH
EXEC SQL INSERT
EXEC SQL LOCK TABLE
-
8/13/2019 Bengkel 1 Guide
6/38
EXEC SQL OPEN
EXEC SQL SELECT
EXEC SQL UPDATE
EXEC SQL COMMIT To process transactions
EXEC SQL ROLLBACK
EXEC SQL SAVEPOINT
EXEC SQL SET TRANSACTION
EXEC SQL DESCRIBE To use dynamic SQL
EXEC SQL EXECUTE
EXEC SQL PREPARE
EXEC SQL ALTER SESSION To control sessions
EXEC SQL SET ROLE
EXEC SQL EXECUTE
END-EXEC
To embed PL/SQL blocks
-
8/13/2019 Bengkel 1 Guide
7/38
CHAPTER 2 CONFIGURING VISUAL STUDIO 2008AND PRO*C
2.1 OBJECTIVES
By the end of this chapter, students should be able to:
Configure Visual Studio 2008 with Pro*C Know how to code to connect to Oracle database
2.2 PREREQUISITES
Before starting this chapter, students are expected to have knowledge in the following
SQL development and syntax Usage of Visual Studio 2008 Oracle Client 10g and Visual Studio 2008 installed in the computer
2.3 CONFIGURATION STEPS
2.3.1 SPECIFYING THE LOCATION OF THE PRO*C/C++EXECUTABLE
1. Start up Visual Studio 2008 2.
Go to Tools> Options. The Options window will open.
3. Expands Projects and Solutionstab in the left panel.4. Select VC++ Directories.
a. On the right panel, select Executable filesfrom Show directories For.b. Then click the new line button (new folder icon) to create a new linec. Click the browse button (button with three dots) and select the folder
ORACLE_BASE\ORACLE_HOME\bin directory. For example :
D:\oracle\product\10.2.0\db_1\bin
d. Note: you should search for the directory in your computer where Oracle isinstalled
5. Click OK.
-
8/13/2019 Bengkel 1 Guide
8/38
3
4
4a
4b
4c
-
8/13/2019 Bengkel 1 Guide
9/38
2.3.2 SPECIFYING THE LOCATION OF THE PRO*C/C++HEADER FILES
1. Go to Tools> Options.2. Expands Projects and Solutionstab in the left panel.3. Select VC++ Directories.
a. On the right panel, select Include Filesfrom Show directories For.b. Then click the new line button (new folder icon) to create a new line c. Click the browse button (button with three dots) and select the folder
ORACLE_BASE\ORACLE_HOME\precomp\public directory. For example :
D:\oracle\product\10.2.0\db_1\precomp\public
d. Note: you should search for the directory in your computer where Oracle isinstalled
4. Click OK.
2
3
3a
3b
3c
-
8/13/2019 Bengkel 1 Guide
10/38
2.3.3 SPECIFYING THE LOCATION OF THE PRO*C/C++LIBRARY FOLDER
Pro*C/C++ applications must link with the library file orasql10.lib to be able to execute.
1. Create a new empty Win32 console application project2. Right click on project, select Properties.
3. Expand Configuration Propertiestab in the left panel.4. Expand Linker. Select General.5. On the right panel, click the browse button (button with 3 dots) in Additional Library
Directories.6. Add a new line (folder icon) and browse for the oraclesql10.lib7. It can found be in ORACLE_BASE\ORACLE_HOME\precomp\lib.
-
8/13/2019 Bengkel 1 Guide
11/38
8. Then, on the left panel, click Input which located under Linkermenu.a. Select Additional Dependencies.b. Then type in orasql10.lib.
9. ClickOK.
3
4
5
8
8b
-
8/13/2019 Bengkel 1 Guide
12/38
-
8/13/2019 Bengkel 1 Guide
13/38
5. After fill the form above, click Add Build Rule.6. Set the rule as shown in the screen capture below.
a. Command Line: proc code=cpp $(InputName)b. Display Name: ProCc. Outputs: $(ProfDir)\$(InputName).cpp
7. Click OK.proc is the command to compile the .pc file.
code=cppspecifies what file extension will it produces. Default is .c files.
$(InputName)is the file name.
6a
6b
6c
-
8/13/2019 Bengkel 1 Guide
14/38
8. Make sure to tick the rule that you created to each project that you want to use proccommand.
-
8/13/2019 Bengkel 1 Guide
15/38
2.3.5 SETTING THE VISUAL STUDIO TO RECOGNIZE .PC AS C/C++CODE
1. Go to Tools > Options2. Expend Text Editor tab in the left panel3. Select File Extension4. Under Extension, typepc and click Add5. Click OK to finish
2
3
4
5
-
8/13/2019 Bengkel 1 Guide
16/38
2.3.6 CONNECT TO ORACLE DATABASE
Setting of the Workpace and Project Properties are done.
Lets create a simple application to try to connect to the Oracle database.
We assume you already have the Oracle userId, password, server IP address and databasename
given by the faculty.
1. Right click Source Files in Project Solutions2. Select Add> New Item
3. Select c++ file and enter the following name for file name TestConnection.pc
-
8/13/2019 Bengkel 1 Guide
17/38
-
8/13/2019 Bengkel 1 Guide
18/38
* connection to database is successful
* this is not needed in the system*/
cout
-
8/13/2019 Bengkel 1 Guide
19/38
* Description: The main calling function
******************************************************************************/
intmain()
{
/*connect to database*/
fnConnectDB();
/*close database connection*/
fnCloseDBConnection();
cout
-
8/13/2019 Bengkel 1 Guide
20/38
10.Right click Source Filesin Project Solutions11.Click Add > Existing Item
12.Browse and add the TestConnection.cppfrom your project folder in you workspace.13.Compile and execute our project. You should get the following output if there is no errors.
-
8/13/2019 Bengkel 1 Guide
21/38
-
8/13/2019 Bengkel 1 Guide
22/38
3.2.3 CONNECT TO DATABASE
Pro*C/C++ program must connect to the database before querying or manipulating data.
CONNECT statement can be used to establish a connection between the application program
and database.
EXEC SQL CONNECT :username IDENTIFIED BY :password ;
where username and password are char or VARCHAR host variables.
Or,
EXEC SQL CONNECT :usr_pwd;
where the host variable usr_pwd contains your username and password separated by a slash
character (/).
3.2.4 USING SELECTSTATEMENT
SELECT, returning single row:EXEC SQL select ename
into :acname from emp
where empno = 7369 ;
SELECT, returning no rows:EXEC SQL select ename
into :acname from emp
where empno = 9999;
SELECT, returning many rows:EXEC SQL select ename
into :acname from emp;
Error handling
Use whenever not found clause
Use Host Array to store
the values
-
8/13/2019 Bengkel 1 Guide
23/38
3.2.5 USING INSERT STATEMENTS
The values can be those of constants, host variables, SQL expressions, SQL functions such as
USER and SYSDATE, or user-defined PL/SQL functions.
Example:
EXEC SQL
INSERT INTO emp (empno, ename, sal, deptno)
VALUES (:emp_number, :emp_name, :salary,
:dept_number);
Using sub query:
EXEC SQL
INSERT INTO emp2 (empno, ename, sal, deptno)
SELECT empno, ename, sal, deptno FROM emp
WHERE job= CLERK);
Using UPDATE and DELETE statments
Example UPDATE statement:
EXEC SQL UPDATE emp
SET sal = :salary, comm = :commission
WHERE empno = :emp_number;
Example DELETE statement:
EXEC SQL DELETE FROM emp
WHERE deptno = :dept_number ;
3.2.6 ERROR HANDLING USING WHENEVERSTATEMENT
WHENEVER statement is used to do automatic checking and error handling
Syntax:
EXEC SQL WHENEVER ;
{ [SQLWARNING] |
[SQLERROR] |
[NOT FOUND]
-
8/13/2019 Bengkel 1 Guide
24/38
}
{ [CONTINUE] |
[DO function_call() | break ]
[goto statement_label] |
[STOP]
}
3.2.7 WHENEVERSTATEMENT -ACTIONS
CONTINUE Continue with next statement if possible
DO {|break|continue} Control transferred to function, at end of routine - control returns to statement
following the failed SQL statement
break - Will break from the loop in which the failed SQL statement is present andtransfer control to statement following loop
GOTO Control transferred to labeled statement
STOP Execution of Program stops, uncommitted work rolled back Generates exit() call
example
void main()
{
//Some piece of code
EXEC SQL DECLARE emp_cursor FOR SELECT
empno,ename FROM emp;
EXEC SQL OPEN emp_cursor;
EXEC SQL WHENEVER NOT FOUND DO break;
-
8/13/2019 Bengkel 1 Guide
25/38
WHILE(1)
{
EXEC SQL FETCH EMP_CURSOR INTO
:EMP_NUMBER,:EMP_NAME;
...
}
EXEC SQL CLOSE EMP_CURSOR;
}
3.3 SAMPLE PROGRAM REVISITED
Lets have a closer look on the previous sample program created in Chapter 2
#include
#include
Includes all the file that
contains the functions for the
execution of the program
voidfnConnectDB()
{
/*host variable declaration*/
EXEC SQL BEGIN DECLARE SECTION;
charconnection_name[128];EXEC SQL END DECLARE SECTION;
/*copy the connection string to host variable*/
strcpy_s(connection_name, "id/pswd@netService");
/*redirect to display error if database error occurs*/
EXEC SQL WHENEVER SQLERROR DO
sql_error("do_connect():CONNECT");
EXEC SQL CONNECT :connection_name;
cout
-
8/13/2019 Bengkel 1 Guide
26/38
-
8/13/2019 Bengkel 1 Guide
27/38
CHAPTER 4 CREATING A SAMPLE MENU DRIVEN CONSOLE DATABASE-
APPLICATION
4.1 OBJECTIVES
By the end of this chapter, students should be able to:
Understand the basic syntax for embedded SQL programming Able to create a simple menu driven Embedded SQL console application
4.2 DATABASE TABLE CREATION
Create the following database tables by executing the sql queries in your oracle
create table customer(
cu_id number(4) constraints cu_pk primary key,
cu_name varchar2(50) constraints cu_name_null not null,
cu_contact varchar2(15) constraints cu_contact_null not null,
cu_status varchar(15) constraints cu_status_null not null
);
create table book(
bo_id number(5) constraints bo_pk primary key,
bo_name varchar2(100) constraints bo_name_null not null,
bo_price number(7,2) constraints bo_price_null not null
);
create table rental_book(
rb_id number(4) constraints rb_pk primary key,
cu_id number(4) constraints rb_fk1 references customer(cu_id) constraints rb_fk1_null
not null,
bo_id number(5) constraints rb_fk2 references book(bo_id) constraints rb_fk2_null not
null,
ev_id number(4) constraints rb_fk3 references event(ev_id),rb_rentaldate date constraints rb_rentaldate_null not null,
rb_returndate date constraints rb_returndate_null not null,
rb_price number(7,2) constraints rb_price_null not null
);
create table event(
-
8/13/2019 Bengkel 1 Guide
28/38
-
8/13/2019 Bengkel 1 Guide
29/38
/* Function declarations */
voidfnConnectDB();
voidfnCloseDBConnection();
voidsql_error(char*);
voidfnMainMenu();
voidfnViewCustomer();voidfnEditCustomer();
voidfnAddCustomer();
/*****************************************************************************
*
* End of Functions.h
******************************************************************************
/
/******************************************************************************
* Filename : Functions.pc
* Author : FTMK, UTeM
* Description : Contains the functions required for opening or closing database
* connections.
* Modification Log:
******************************************************************************
/
/* Include files */#include
#include
#include
/* Declaration of functions and constants used */
#include"Functions.h"
usingnamespacestd;
/*****************************************************************************
*
* Function: fnConnectDB
* Description: Connect to Oracle 10g Database
******************************************************************************
/
voidfnConnectDB()
-
8/13/2019 Bengkel 1 Guide
30/38
{
/*host variable declaration*/
EXEC SQL BEGIN DECLARE SECTION;
charconnection_name[128];
EXEC SQL END DECLARE SECTION;
/*copy the connection string to host variable*/strcpy_s(connection_name, "/@");
/*redirect to display error if database error occurs*/
EXEC SQL WHENEVER SQLERROR DO sql_error("do_connect():CONNECT");
EXEC SQL CONNECT :connection_name;
/*********/
/* this code is to print the connection statement to verify the connection
* is successful. Uncomment this if you want to verify whether the
* connection to database is successful* this is not needed in the system*/
//printf("Connected to database.\n");
cout
-
8/13/2019 Bengkel 1 Guide
31/38
{
charmessage_buffer[512];
size_t buffer_size;
size_t message_length;
/* Turn off the call to sql_error() to avoid a possible infinite loop */EXEC SQL WHENEVER SQLERROR CONTINUE;
cout
-
8/13/2019 Bengkel 1 Guide
32/38
/* Declaration of functions and constants used */
#include"Functions.h"
usingnamespacestd;
/*****************************************************************************
*
* Function: fnViewCustomer
* Description: Page to add new customer
******************************************************************************
/
voidfnViewCustomer()
{
EXEC SQL BEGIN DECLARE SECTION;
intcustomer_id;charname[25],contact[15];
charstatus[20];
EXEC SQL END DECLARE SECTION;
inttotalCustomer=0;
fnConnectDB();
system("cls");
cout
-
8/13/2019 Bengkel 1 Guide
33/38
cout
-
8/13/2019 Bengkel 1 Guide
34/38
cin>>cu_id;
cin.clear();
cin.ignore(numeric_limits::max(),'\n');
EXEC SQL SELECT * INTO :customer_id,:name,:contact,:status FROM CUSTOMER WHERE
CU_ID = :cu_id;
cout
-
8/13/2019 Bengkel 1 Guide
35/38
-
8/13/2019 Bengkel 1 Guide
36/38
cin.ignore(numeric_limits::max(),'\n');
cin.get();
system("cls");
fnCloseDBConnection();
fnMainMenu();
}
/*****************************************************************************
*
* End of Customer.pc
******************************************************************************
/
/*****************************************************************************
*
* Filename : Main.cpp
* Author : FTMK, UTeM
* Description : Contains the functions required for main module of the system
* Modification Log:
******************************************************************************
/
/* Include files */#include
#include
/* Declaration of functions and constants used */
#include"Functions.h"
usingnamespacestd;
/*****************************************************************************
*
* Function: fnMainMenu
* Description: Menu for the customer
******************************************************************************
/
voidfnMainMenu()
{
-
8/13/2019 Bengkel 1 Guide
37/38
intchooice = 0;
cout
-
8/13/2019 Bengkel 1 Guide
38/38
intmain()
{
fnMainMenu();
return0;
}
/*****************************************************************************
*
* End of DBFunctions.c
******************************************************************************
/
2. Change the database connection userid, password and host String in Function.pc3.
Compile all the .pc files and add the generated .cpp files into the project source.
4. Execute the program and observe the output.5. Try to add a Customer.6. Display all the customers in the system.7. Edit Customer 1001 and change all his information.8. File does not have header guard. So you need to type codes like example below to avoid conflict
before you include .
#defineSQLCA_STORAGE_CLASS extern
4.4 EXERCISE
In the sample program given above, the add book and view books modules are not
implemented.
1. Create a Books.pcfile and implement necessary functions to add book and view book2. Call the functions u created in Book.pcin Main.pcsfn in enufunction