Vous êtes sur la page 1sur 38

TABLE OF CONTENTS

Chapter 1 1.1 1.2 Introduction to Embedded SQL ........................................................................................ 3 Objectives................................................................................................................................ 3 Introduction ............................................................................................................................ 3 Embedded SQL statements .............................................................................................. 3 PRO*C .............................................................................................................................. 3 Steps in executing PRO*C program .................................................................................. 4 List of embedded SQL statements supported by Pro*C ................................................... 5 Configuring Visual Studio 2008 and Pro*c........................................................................ 7

1.2.1 1.2.2 1.2.3 1.2.4 Chapter 2 2.1 2.2 2.3

Objectives................................................................................................................................ 7 prerequisites ........................................................................................................................... 7 Configuration steps ................................................................................................................. 7 Specifying the Location of the Pro*C/C++ Executable ..................................................... 7 Specifying the Location of the Pro*C/C++ Header Files .................................................... 9 Specifying the Location of the Pro*C/C++ Library folder ................................................ 10 Setting Custom Build for .pc extension .......................................................................... 12 Setting the Visual Studio to recognize .pc as C/C++ code ............................................... 15 Connect to Oracle database ........................................................................................... 16 Introduction to Embedded SQL Programming ............................................................... 21

2.3.1 2.3.2 2.3.3 2.3.4 2.3.5 2.3.6 Chapter 3 3.1 3.2

Objectives.............................................................................................................................. 21 Introduction .......................................................................................................................... 21 Embedded SQL syntax.................................................................................................... 21 Host Variables ................................................................................................................ 21 Connect to database ...................................................................................................... 22 Using SELECT statement ................................................................................................. 22 Using INSERT Statements............................................................................................... 23 Error Handling using WHENEVER statement .................................................................. 23 WHENEVER statement - Actions .................................................................................... 24

3.2.1 3.2.2 3.2.3 3.2.4 3.2.5 3.2.6 3.2.7 3.3

Sample Program Revisited ..................................................................................................... 25 Creating a sample menu driven console database-application ...................................... 27

Chapter 4 4.1

Objectives.............................................................................................................................. 27

4.2 4.3 4.4

Database Table Creation ....................................................................................................... 27 Program Development .......................................................................................................... 28 Exercise ................................................................................................................................. 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 SQL STATEMENTS 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 control access 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 then run the precompiler (the command is proc) on your source and out comes a new source file that you can compile as usual.

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*C PROGRAM

1.2.4 LIST OF EMBEDDED SQL STATEMENTS SUPPORTED BY PRO*C Declarative Statements


EXEC SQL ARRAYLEN EXEC SQL BEGIN DECLARE SECTION EXEC SQL END DECLARE SECTION EXEC SQL DECLARE EXEC SQL INCLUDE EXEC SQL TYPE EXEC SQL VAR EXEC SQL WHENEVER To name Oracle objects To copy in files To equivalence datatypes To equivalence variables To handle runtime errors To use host arrays with PL/SQL To declare host variables

Executable Statements
EXEC SQL ALLOCATE 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 EXEC SQL EXPLAIN PLAN EXEC SQL FETCH EXEC SQL INSERT EXEC SQL LOCK TABLE To query and manipulate Oracle data To define and control Oracle data

EXEC SQL OPEN EXEC SQL SELECT EXEC SQL UPDATE EXEC SQL COMMIT EXEC SQL ROLLBACK EXEC SQL SAVEPOINT EXEC SQL SET TRANSACTION EXEC SQL DESCRIBE EXEC SQL EXECUTE EXEC SQL PREPARE EXEC SQL ALTER SESSION EXEC SQL SET ROLE EXEC SQL EXECUTE END-EXEC To embed PL/SQL blocks To control sessions To use dynamic SQL To process transactions

CHAPTER 2 CONFIGURING VISUAL STUDIO 2008 AND 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
2.3.1

CONFIGURATION STEPS
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 Solutions tab in the left panel. 4. Select VC++ Directories. a. On the right panel, select Executable files from 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\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 is installed 5. Click OK.

3 4

4a

4b

4c

2.3.2 SPECIFYING THE LOCATION OF THE PRO*C/C++ HEADER FILES 1. Go to Tools > Options. 2. Expands Projects and Solutions tab in the left panel. 3. Select VC++ Directories. a. On the right panel, select Include Files from 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 is installed 4. Click OK.

2 3 3b 3c

3a

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 project 2. Right click on project, select Properties.

3. Expand Configuration Properties tab 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.lib 7. It can found be in ORACLE_BASE\ORACLE_HOME\precomp\lib.

8. Then, on the left panel, click Input which located under Linker menu. a. Select Additional Dependencies. b. Then type in orasql10.lib. 9. Click OK.

8b

2.3.4 SETTING CUSTOM BUILD FOR .PC EXTENSION Pro*C/C++ files have .pc extension. So it must be compiled with the proc command to produce the .cpp files. 1. Right click on project, select Custom Build Rules.

2. Click New Rules File.

Specify where do you want to save this rule.

3. Fill in ProC for Display Name and File Name. 4. Browse to a directory where you want to store the Rule file. Make sure the file created is always available and not deleted.

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: ProC c. Outputs: $(ProfDir)\$(InputName).cpp

6a

6b

6c

7. Click OK. proc is the command to compile the .pc file. code=cpp specifies what file extension will it produces. Default is .c files. $(InputName) is the file name.

8. Make sure to tick the rule that you created to each project that you want to use proc command.

2.3.5 SETTING THE VISUAL STUDIO TO RECOGNIZE .PC AS C/C++ CODE 1. Go to Tools > Options 2. Expend Text Editor tab in the left panel 3. Select File Extension 4. Under Extension, type pc and click Add 5. Click OK to finish

4 2

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 Solutions 2. Select Add > New Item

3. Select c++ file and enter the following name for file name TestConnection.pc

4. Click Add to create a new file 5. Note: always remember to use .pc file extension for embedded SQL programming 6. Enter the following code in the TestConnection.pc file created
/****************************************************************************** * Filename : TestConnection.pc * Author : FTMK, UTeM * Description : Contains the functions required for opening or closing database * connections. * Modification Log: ******************************************************************************/ /* Include files */ #include <iostream> #include <sqlca.h> #include <sqlcpr.h> using namespace std; /* function declarations */ void fnCloseDBConnection(); void fnConnectDB(); void sql_error(char *routine); /****************************************************************************** * Function: fnConnectDB * Description: Connect to Oracle 10g Database ******************************************************************************/ void fnConnectDB() { /*host variable declaration*/ EXEC SQL BEGIN DECLARE SECTION; char connection_name[128]; EXEC SQL END DECLARE SECTION; /*copy the connection string to host variable*/ strcpy_s(connection_name, "<userid>/<password>@<service 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*/ cout<<"Connected to database.\n"<<endl; } /****************************************************************************** * Function: fnCloseConnectionDB * Description: Closes and commits the database connection ******************************************************************************/ void fnCloseDBConnection() { /*close database connection*/ EXEC SQL COMMIT WORK RELEASE; } /****************************************************************************** * Function: sql_error * Description: Generic error handler. The 'routine' parameter should contain * the name of the routine executing when the error occured. This would be * specified in the 'EXEC SQL WHENEVER SQLERROR DO sql_error()' statement. * Input Parameters: * char *routine ******************************************************************************/ void sql_error(char *routine) { char message_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<<"\nOracle error while executing "<<routine<<"!\n"; /* Use sqlglm() to get the full text of the error message. */ buffer_size = sizeof(message_buffer); sqlglm(message_buffer, &buffer_size, &message_length); cout<<message_length<<", "<<message_buffer<<"\n"; EXEC SQL ROLLBACK WORK RELEASE; exit(1); } /****************************************************************************** * Function: main

* Description: The main calling function ******************************************************************************/ int main() { /*connect to database*/ fnConnectDB(); /*close database connection*/ fnCloseDBConnection(); cout<<"Database connection closed"<<endl; return 0; } /****************************************************************************** * End of DBFunctions.c ******************************************************************************/

**Note: at the code "<userid>/<password>@<service name>, remember to change to your database userid, password, and Oracle Net Service name given and configured in your computer. Example: B03100057/password@sunftmk 7. After changing the Oracle connection settings, right click TestConnection.pc and click Compile.

8. If all your configurations and code is correct, the compilation should succeed. 9. *Note, a corresponding .cpp file will be generated whenever you compile a .pc file. You MUST include the generated .cpp file into the project after u compile a .pc file for the first time. DO NOT EDIT the generated .cpp file.

10. Right click Source Files in Project Solutions 11. Click Add > Existing Item

12. Browse and add the TestConnection.cpp from your project folder in you workspace. 13. Compile and execute our project. You should get the following output if there is no errors.

CHAPTER 3 INTRODUCTION TO EMBEDDED SQL PROGRAMMING


3.1 OBJECTIVES

By the end of this chapter, students should be able to: Understand the basic syntax for embedded SQL programming

3.2

INTRODUCTION

3.2.1 EMBEDDED SQL SYNTAX Must begin with the keywords EXEC SQL and end them with a semicolon. Example: EXEC SQL INSERT INTO branch (bcode,location) VALUES (:br_code.:br_location); Pro*C/C + + translates all EXEC SQL statements into calls to the runtime library SQLLIB. Many embedded SQL statements differ from their interactive counterparts only through the addition of a new clause or the use of program variables. 3.2.2 HOST VARIABLES Used to achieve the communication between Oracle and Application program In SQL statements, host variables must be prefixed with a colon (:) The host variable declarations can be placed wherever C variable declarations can be placed. A host variable must not be Used as an array subscript Prefixed with colon in host language statements. Cannot use input host variables to supply SQL keywords or the names of the database objects. In the following example, the DROP TABLE statement is invalid: char table_name[30]; cout<<"Table name? "<<endl; cin>>table_name; EXEC SQL DROP TABLE :table_name;<--host variable not allowed

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 SELECT STATEMENT 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; Use Host Array to store the values Error handling Use whenever not found clause

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 WHENEVER STATEMENT WHENEVER statement is used to do automatic checking and error handling Syntax: EXEC SQL WHENEVER <condition> <action>; <condition> { [SQLWARNING] | [SQLERROR] | [NOT FOUND]

} <action> { [CONTINUE] | [DO function_call() | break ] [goto statement_label] | [STOP] }

3.2.7 WHENEVER STATEMENT - ACTIONS CONTINUE Continue with next statement if possible DO {<function>|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 and transfer control to statement following loop GOTO <label> 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;

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 <sqlca.h> #include <sqlcpr.h> Includes all the file that contains the functions for the execution of the program

void fnConnectDB() { /*host variable declaration*/ EXEC SQL BEGIN DECLARE SECTION; char connection_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<<"Connected to database.\n"<<endl; }

This function will establish a connection to the database. Host variable MUST be declared between the EXEC SQL BEGIN DECLARE SECTION and EXEC SQL END DECLARE SECTION *Each connetion will create adatabase session in the server, it is best practice to close the connection after use

void fnCloseDBConnection() { /*close database connection*/ EXEC SQL COMMIT WORK RELEASE; } void sql_error(char *routine) { char message_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<<"\nOracle error while executing "<<routine<<"!\n"; /* Use sqlglm() to get the full text of the error message. */ buffer_size = sizeof(message_buffer); sqlglm(message_buffer, &buffer_size, &message_length); cout<<message_length<<", "<<message_buffer<<"\n"; EXEC SQL ROLLBACK WORK RELEASE; exit(1); }

This function will close a database connection.

This function will display error message generated from database query failure and close the close the database connection. The system will then exit. Note the function fnConnectDB calls this to display error message if there is any error in establish connection to the database server

CHAPTER 4 CREATING A SAMPLE MENU DRIVEN CONSOLE DATABASEAPPLICATION

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(

ev_id number(4) constraints ev_pk primary key, ev_name varchar2(50) constraints ev_name_null not null, ev_date date constraints ev_date_null not null, ev_rate number(5,2) constraints ev_rate_null not null ); insert into customer values(1001,'Ali','026-8175124','MEMBER'); insert into customer values(1002,'Ahmad','014-7194012','NON-MEMBER'); insert into book values(10001,'Oracle SQL Tutorial for Beginner',1.00); insert into book values(10002,'Oracle PL/SQl Tutorial for Beginner',1.50); insert into event values(1,'Member Day',TO_DATE('01-09-2011','dd-mm-yyyy'),0.50); insert into event values(2,'Christmas Discount',TO_DATE('16-12-11','dd-mm-yyyy'),0.90); insert into rental_book(rb_id,cu_id,bo_id,rb_rentaldate,rb_returndate,rb_price) values (1,1001,10001,TO_DATE('6-07-2011','dd-mm-yyyy'),TO_DATE('11-07-2011','dd-mmyyyy'),5.00); insert into rental_book(rb_id,cu_id,bo_id,rb_rentaldate,rb_returndate,rb_price) values (2,1001,10002,TO_DATE('6-07-2011','dd-mm-yyyy'),TO_DATE('11-07-2011','dd-mmyyyy'),7.50); *Remember to execute the COMMIT command to make sure data is written to the server permanently

4.3

PROGRAM DEVELOPMENT

1. Create a new Project in Visual studio and create the following .cp files and .h file. /***************************************************************************** * * Filename : Functions.h * Author : FTMK, UTeM * Description : Declaration of functions and constants required to use the * functions defined in Functions.cpp and other files * Modification Log: ****************************************************************************** / /* Pre-defined constants */ /* Oracle error code for 'table or view does not exist'. */ #define NON_EXISTENT -942 #define NOT_FOUND 1403

/* Function declarations */ void fnConnectDB(); void fnCloseDBConnection(); void sql_error(char *); void fnMainMenu(); void fnViewCustomer(); void fnEditCustomer(); void fnAddCustomer(); /***************************************************************************** * * 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 <iostream> #include <sqlca.h> #include <sqlcpr.h> /* Declaration of functions and constants used */ #include "Functions.h" using namespace std; /***************************************************************************** * * Function: fnConnectDB * Description: Connect to Oracle 10g Database ****************************************************************************** / void fnConnectDB()

{ /*host variable declaration*/ EXEC SQL BEGIN DECLARE SECTION; char connection_name[128]; EXEC SQL END DECLARE SECTION; /*copy the connection string to host variable*/ strcpy_s(connection_name, "<id>/<pswd>@<host_string>"); /*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<<"Connected to database.\n"<<endl; } /***************************************************************************** * * Function: fnCloseConnectionDB * Description: Closes and commits the database connection ****************************************************************************** / void fnCloseDBConnection() { /*close database connection*/ EXEC SQL COMMIT WORK RELEASE; } /***************************************************************************** * * Function: sql_error * Description: Generic error handler. The 'routine' parameter should contain * the name of the routine executing when the error occured. This would be * specified in the 'EXEC SQL WHENEVER SQLERROR DO sql_error()' statement. * Input Parameters: * char *routine ****************************************************************************** / void sql_error(char *routine)

{ char message_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<<"\nOracle error while executing "<<routine<<"!\n"; /* Use sqlglm() to get the full text of the error message. */ buffer_size = sizeof(message_buffer); sqlglm(message_buffer, &buffer_size, &message_length); cout<<message_length<<", "<<message_buffer<<"\n"; EXEC SQL ROLLBACK WORK RELEASE; exit(1); } /***************************************************************************** * * End of Functions.pc ****************************************************************************** /

/***************************************************************************** * * Filename : Customer.pc * Author : FTMK, UTeM * Description : Contains the functions required for customer modules * Modification Log: ****************************************************************************** / /* Include files */ #include <iostream> #include <string> #include <limits> #include <iomanip> #define SQLCA_STORAGE_CLASS extern #include <sqlca.h>

/* Declaration of functions and constants used */ #include "Functions.h" using namespace std; /***************************************************************************** * * Function: fnViewCustomer * Description: Page to add new customer ****************************************************************************** / void fnViewCustomer() { EXEC SQL BEGIN DECLARE SECTION; int customer_id; char name[25],contact[15]; char status[20]; EXEC SQL END DECLARE SECTION; int totalCustomer=0; fnConnectDB(); system("cls"); cout<<"\n\t======================="; cout<<"\n\tWelcome to Library UTeM\n"; cout<<"\t=======================\n\n"; cout<<" View All Customer Details\n\n"; cout<<"Id\tName\t\t\t\tContact\t\tStatus\n"; cout<<setfill('-')<<setw(66)<<"-"<<endl; EXEC SQL DECLARE customerReportCursor CURSOR FOR select * from customer; EXEC SQL OPEN customerReportCursor; /* loop through the cursor and break the loop when end*/ EXEC SQL WHENEVER NOT FOUND DO break; while (1) { /* fetch the data from cursor and display*/ EXEC SQL FETCH customerReportCursor INTO :customer_id, :name, :contact, :status;

cout<<customer_id<<"\t"<<name<<" "<<contact<<"\t"<<status<<endl; totalCustomer++; } EXEC SQL WHENEVER NOT FOUND CONTINUE; EXEC SQL CLOSE customerReportCursor; cout<<"\nTotal customer : "<<totalCustomer<<endl; cout<<"\nPress any key to return to menu"; cin.get(); system("cls"); fnCloseDBConnection(); fnMainMenu(); } /***************************************************************************** * * Function: fnAddCustomer * Description: Page to add new customer ****************************************************************************** / void fnEditCustomer() { EXEC SQL BEGIN DECLARE SECTION; int customer_id,cu_id; char name[50],contact[15]; char status[20]; EXEC SQL END DECLARE SECTION; int chooice = 0; int stat; fnConnectDB(); system("cls"); cout<<"\n\t======================="; cout<<"\n\tWelcome to Library UTeM\n"; cout<<"\t=======================\n\n"; cout<<" Edit A Customer\n\n"; cout<<"Customer Id\t\t: ";

cin>>cu_id; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); EXEC SQL SELECT * INTO :customer_id,:name,:contact,:status FROM CUSTOMER WHERE CU_ID = :cu_id; cout<<"\nCustomer Id\t\t: "<<customer_id; cout<<"\nCustomer Name\t\t: "<<name; cout<<"\nCustomer contact\t: "<<contact; cout<<"\nCustomer status\t\t: "<<status; cout<<"\n\nEnter new value for customer:\n\n"; cout<<"Customer name\t\t: "; cin.getline(name,50); cout<<"Customer contact\t: "; cin.getline(contact,15); cout<<"\n\t1 - Member"; cout<<"\n\t2 - Non-member\n"; cout<<"\nCustomer status\t\t: "; cin>>stat; if(stat == 1) strcpy_s(status,"MEMBER"); else if(stat == 2) strcpy_s(status,"NON-MEMBER"); EXEC SQL UPDATE CUSTOMER SET cu_name=:name,cu_contact=:contact,cu_status=:status WHERE cu_id = :customer_id;

cout<<"\nCustomer record has been updated\n\n"; cout<<"Press any key to return to menu"; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); cin.get(); system("cls"); fnCloseDBConnection(); fnMainMenu(); } /***************************************************************************** *

* Function: fnAddCustomer * Description: Page to add new customer ****************************************************************************** / void fnAddCustomer() { EXEC SQL BEGIN DECLARE SECTION; int customer_id; char name[50],contact[15]; char status[20]; EXEC SQL END DECLARE SECTION; int chooice = 0; int stat; fnConnectDB(); EXEC SQL SELECT MAX(cu_id) into :customer_id from CUSTOMER; customer_id++; system("cls"); cout<<"\n\t======================="; cout<<"\n\tWelcome to Library UTeM\n"; cout<<"\t=======================\n\n"; cout<<" Add New Customer\n\n"; cout<<"Customer name\t\t: "; cin.getline(name,50); cout<<"Customer contact\t: "; cin.getline(contact,15); cout<<"\n\t1 - Member"; cout<<"\n\t2 - Non-member\n"; cout<<"\nCustomer status\t\t: "; cin>>stat; if(stat == 1) strcpy_s(status,"MEMBER"); else if(stat == 2) strcpy_s(status,"NON-MEMBER"); EXEC SQL INSERT INTO CUSTOMER VALUES(:customer_id,:name,:contact,:status); cout<<"\nCustomer record has been inserted\n\n"; cout<<"Press any key to return to menu";

cin.ignore(numeric_limits<streamsize>::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 <iostream> #include <limits> /* Declaration of functions and constants used */ #include "Functions.h" using namespace std;

/***************************************************************************** * * Function: fnMainMenu * Description: Menu for the customer ****************************************************************************** / void fnMainMenu() {

int chooice = 0; cout<<"\n\t======================="; cout<<"\n\tWelcome to Library UTeM\n"; cout<<"\t=======================\n\n"; cout<<"1. Add new customer\n"; cout<<"2. Update a customer\n"; cout<<"3. Report on Customer\n"; cout<<"4. Add Book\n"; cout<<"5. Report on Book\n"; cout<<"6. Exit system\n"; cout<<"\n >> "; cin>>chooice; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); switch(chooice){ case 1 : fnAddCustomer(); break; case 2 : fnEditCustomer(); break; case 3 : fnViewCustomer(); break; case 4 : break; case 5 : break; case 6 : break; default : exit(1); } } /***************************************************************************** * * Function: main * Description: The main calling function ****************************************************************************** /

int main() { fnMainMenu(); return 0; } /***************************************************************************** * * End of DBFunctions.c ****************************************************************************** /

2. Change the database connection userid, password and host String in Function.pc 3. 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 <sqlca.h> does not have header guard. So you need to type codes like example below to avoid conflict
before you include <sqlca.h>. #define SQLCA_STORAGE_CLASS extern <sqlca.h>

4.4

EXERCISE

In the sample program given above, the add book and view books modules are not implemented. 1. Create a Books.pc file and implement necessary functions to add book and view book 2. Call the functions u created in Book.pc in Main.pcs fnMainMenu function

Vous aimerez peut-être aussi