Thursday, 30 January 2014



Are you looking for alternate of group by clause?
Consider the scenario, We have to fetch the count of birthday of all students in the particular dept along with the college_id field.
If college id field was not there then, we can use the following query

select dept_id,count(*) from profile where Bday=’08/29/1992’ group by Bday;

The above query will work fine but, If we want to include College_id field in the result_set the below query will return error. This is because group by is used for aggregate functions. Here For particular dept there may be several college_id’s. As like CSE is present in various colleges.

select college_ID,Dept_id,count(Bday) from profile where Bday=’08/29/1992’ group by Bday;  -- ERROR QUERY --

So workaround is , you have to use the partition clause

select college_ID,Dept_id,count(Bday) over (partition by dept_id) from profile where Bday=’08/29/1992’ group by Bday;  -- ERROR QUERY --

This will return the following output:

COLL_ID  DEPT_ID         COUNT
1               10                    5
2               12                    2
This shows that, at college 1 , in dept 10, 5 students have birthday at  01/29/1992      

Here the college id  and dept id should be primary.


Tuesday, 28 January 2014


COMMIT:

EXEC SQL COMMIT WORK RELEASE;
COMMIT and COMMIT WORK are one and same. No difference in it. It is made for standards. Release is to release all the resources hold by your program.
We can also comment on commit statement using the COMMENT clause followed by soft coded literals

EXEC SQL COMMIT COMMENT ‘SAVED EMP SALARY’;
Comment clause is depreciated in the future release of oracle and transaction based on the name is introduced.

SET TRANSACTION
EXEC SQL SET TRANSACTION READ ONLY
The above code makes the transaction to the read only state. In order to exit from the read only state we have to Commit/Rollback the work.

Inline precompiler option:
EXEC ORACLE (option=value);

Naming Files:
The filenames should not contain spaces for proc. For Eg some of the filenames or directory names will contain space in windows.
Placing inside the program:

For embedding the sql statemet in PRO *C/C++:

For embedding the sql statemet in PRO *C/C++
EXEC SQL /* SQL STATEMENT GOES HERE */ ;
For embedding the PL/SQL statement.
EXec sql execute /* pl sql block goes here */ end-exec

Comments lines:
/**/ Multiline comment
You can also use the ANSI-Style comments such as (--…)
datatype equivalencing:
Giving the flexibility of using the both oracle datatype and c datatype as same type.

Shared & Private sql areas:
When two users execute the same type of  query then the oracle will execute in the shared sql area. But they will have a separate sql statement in the sql private areas. In Pro *C/C++ Cursor will name the sql statement and to some extent it  controls the sql statement.

Cursor
used for handling result of more than one dataset.  The set of rows returned is called as an active set. There are two types of cursors
1.      Implicit cursor
2.      Explicit cursor
The Explicit cursor are used to find which row is currently processing.

Transaction:
The changes that are made at two or more than two end points due to some activity. Endpoints may be the bank accounts and the changes may be the amount.

Line continuation:
If you want to  continue the same sql statement in next line then use a backslash. Maximum line length is 1299.
exec sql insert into marks values(‘vino\
th’,100,12,4\
5);


Maxliterals:
Constant used to restrict the precompiler for Maximum literal length to be allowed for the string because the C compiler may be restricted to certain length.
conditional precompilation:

Conditional precompilation statement will include
STATEMENT
DEFINITION
EXEC ORACLE DEFINE
DEFINES THE STATEMENT
EXEC ORACLE IFDEF
IF DEFINITION WAS FOUND
EXEC ORACLE IFNDEF
IF DEF NOT FOUND
EXEC ORACLE ELSE
ELSE CONDITION



Cursor in modular programming:

Pro c allows for the modular programming. Where the programs can be built in different areas and we can link them together. Cursor should be defined in  each modules because the precompiler will convert the all cursor declaration to a C statements.


Explicit lock:

EXEC SQL LOCK TABLE EMP IN ROW SHARE MODE NOWAIT;

Monday, 27 January 2014




The sample code to connect the database…

#include<stdio.h>
#include<string.h>
//#include"sqlca.h"

EXEC SQL INCLUDE sqlca;
EXEC SQL BEGIN DECLARE SECTION;
 char *username="vinoth_db";
 char *pwd="vinoth_db123";
 char *str="vino";
EXEC SQL END DECLARE SECTION;

int main()
{
   EXEC SQL WHENEVER SQLERROR GOTO sqlerr;
   EXEC SQL COnneCT :username IDENTIFIED BY :pwd USING :str;
   printf("Success Connecting with database!");
   return 0;

sqlerr:
   printf("Error occured in connecting with database");
}

OUTPUT:
Success Connecting with database!

DESCRIBTION OF THE PROGRAM:

EXEC SQL INCLUDE SQLCA;
#INCLUDE ”/PATH/TO/SQLCA”       
The above file is to be included in the proc file to connect with the databases. The above file will contain the information to connect with the databases. The difference between the first and second line is, the first line is a SQL statement. In that we no need to specify the path of the file SQL will refer it internally. But in the second line we need to specify the path of the file.


EXEC SQL BEGIN DECLARE SECTION;
EXEC SQL END DECLARE SECTION;

All the variable that are used with the EXEC SQL statements are need to be declared under these two lines. If variables are not declared under this lines then SQL precompile will show error. For eg in above code, if variable username is declared outside this then the precompilation will throw error.

EXEC SQL WHENEVER SQLERROR GOTO sqlerr;
Whenever the error occurs in the database then program control will be directed to sqlerr label. For instance when  you give the username or password wrongly then sqlerr label will be executed.

EXEC SQL COnneCT :username IDENTIFIED BY :pwd USING :str;
This statement is used to connect with the database. Here I have given connect as COnneCT. there is no special meaning for that. Since the proc is not case sensitive I have written like that. Using statement defines the string that can be used to connect the oracle DB’s.
you can use the input variable for username, pwd as char pointer or VARCHAR.
other forms of connect statement:

   EXEC SQL CONNECT : “vino_db/vino_db123@vino”
This is simplest form of connect statement. You can connect like this too. Just give the connection string to connect phrase.

Here the connection string is combination of username,pwd,oracle string.


Advanced connection technique:

EXEC SQL DECLARE DB_NAME1 DATABASE:
The above statement will give a unique name to the database connection. we have to use the above declared stamen while connecting to the database. For instance

exec sql connect:”abc/abc123” at DB_NAME1;
The above code will connect to the datebase with a name of db_name1;
Don’t use semicolon for at clause; The db_name1 is not host or program variable. It is just a identifier used by the oracle. No need to declare too. As a exception we can use host variable for at clause too. If we use a host variable no need to use the “Declare db_name1 database” statement.

EXEC SQL AT DB_NAME1 INSERT IN TO …………

Execute the sql operation by preceeding with the at clause. For cursors no need to use at clause for open,fetch etc. we need to mention only at the Declare statement of the cursor. 

Sunday, 26 January 2014


There are  two types of datatypes in pro *c/c++. They are
1.      Internal Datatype
2.      External datatype

Internal Datatype:

long:
Long datatype was not used now. They are depreciated. It belongs to the char family. We can use the long datatyoe if we have backward compatability.
It is now replaced by LOB.

varchar2 & varchar:
varchar is reserved by oracle for future use. ANSI says that “NULL” and empty string are two different things. So if you rely on that use Varchar if not use VARCHAR2.

size of the varchar can be represented in two forms.
1.      memory size
2.      Number of char

Always rely on number of char because we cannot be sure that how many bytes the single character will take. It depend upon the area we use.

Varchar is defined as structure by the precompiler.
Varchar contains the two members  such as arr and len. arr member contains the value where as len contains the len of the arr. while fetching the database the two fields will be updated. But while giving as input to database, it is the responsibility of the programmer to fill those members.

Typically, the arr is  filled with strncpy statement.

char username=”vino_db”;
Varchar user_DB[10];

user_DB.len=strlen(username);
strncpy((char *)user_DB.arr,username,user_DB.len);
user_DB.arr[user_DB.len+1]=’\0’;

Don’t fail to give the declaration of VARCHAR under the declare section. The size to be mentioned while declaring the varchar.

FLOAT DATATYPE

It is an alias for an real or double precision datatype. Real in precision is 23 or less. Whereas Double is 24 or greater.



There are two types of variables in pro *C/C++.
1.      Host variable
2.      Indicator Variable

Both the Host and Indicator variable will prefix with the semicolon to differentiate with the normal variable. We can also use the struct as host variable by prefixing the struct with the semicolon.

Host Variable:
The host variable is used for communicating between the oracle Database and proc language. For eg if we want to retrieve the data from the database and use that data in programming we can use the host variable.

EXEC SQL select  AGE into :age_HV  :age_IV  from PROFILE where  EMP_ID = :EMPID_HV;
In this statement age_HV is the host variable. After successful execution of select statement, age of the given employee will be copied to age_HV.

Indicator variable:
The indicator variable is one which states the condition of the  host variable. It is the short integer.

EXEC SQL select  AGE into :age_HV  :age_IV  from PROFILE where  EMP_ID = :EMPID_HV;
In this statement age_IV is the indicator variable. If this variable  is assigned as 0 after executing the select statement then it indicates that age is copied to host variable age_HV. If it is -1 , then it indicates that value is not fetched. That’s why it is called as indicator variable.

Host array:
It is used to handle the multiple data at a stretch.




Socket is basically an end point of an Inter process communication.

Wonder what is Interprocess communication?

It is the process of communicating between the two threads(process), that run on the system concurrently.
Sockets are bidirectional. That is we can send and receive data at both of the ends. This is point to point communication and communication in socket will happen as connection oriented(stream) or connection less(datagrams).
Socket address:

Socket address is the combination of IP address and port numbers.

IP address is address that uniquely identifies your computer. when you are transferring the packet from one computer to other computer. you need a IP address to transfer it. It like a address which we give to courier man. Upon reaching the destination, you need to find for which member of the family the courier has been arrived. It may be for you, or for your brother, mother. How to find that? For that purpose the port number is used. As such there are different members in the family there will be several process running on the system. Here the port number decides for which process the packet has to be delivered. Here the family members can be http, SSH, HTTP secure, web browser. For this some port number will be user defined and predefined also. Predefined are take cared by IANA(internet assigned numbers authority)

API:

There is no built in programs in c for sockets. Widely there is two API available..
1.      BSD sockets (Berkeley socket distribution)
2.      winsock (Windows sockets)


Socket programming you have written is an part of application layer. All the low level code are covered by Berkeley in BSD socket programming. we use the application programming interface in the application layer.

Saturday, 25 January 2014


Pro c is the embedded SQL programming language. It is used in the oracle databases for manipulating the databases. It is based on the ANSI C compliance and also supports the multithread Programming. The extension of Proc  file is .pc
First precompile the proc file to produce a respective c/c++ file.
To precompile the pro *C/C++ file you need just type the following command.

proc filename.pc

While precompiling the proc file the oracle gives some options in form of name value pairs. This options were used to configure according to our needs.

There are several parameters to be configured before you precompile the proc file.

1. Make sure that $ORACLE_HOME environmental variable is set Correctly.
If not path is correctly set, Set using the following command in your terminal.
$ORACLE_PATH=/…/…/../../Oracle/10.0.0.1/orcl
To verify the path set use the following command
echo $ORACLE_PATH

2. Export the $ORACLE_HOME to your currently working shell.
Eg export $ORACLE_PATH

3. LD_LIBRARY_PATH. This is the environmental variable in linux that contains the list of dynamic linking files. Make sure that LD_LIBRARY_PATH is set correctly.

4.  In case the ELF(Executable and linking format) error occurs then you are making some mistakes with the portability (32 to 64 bit portability ,64 bit 32 bit portability)

when that error occurs i.e., while compiling the precompiled code,  use m-64 or m-32 option in gcc. It is used for compiling the code as 32 or 64 bit.


After Precompilation:

After Precompiling the proc file,  then corresponding cpp file will be generated. Then that cpp file need to be compiled like this

g++ connect.cpp  -L/path/to/oracle/10.2.0/db_1/lib -lclntsh -m64

Friday, 24 January 2014





Garbage value will be initialized if we use this format.
int  arr[10];

In this case all the elements of the array will be initialized to zero because of the keyword static.
static int arr[10];

This code will initialize the all elements of the array to zero.
int arr[10]={0};

This  will initialize the all elements of the array to zero.
int arr[10]={};

This will initialize the first two elements of the array as initialized and remaining all elements will be initialized as zero.
int arr[10]={1,2}

This kind of initialization is not possible in c program. You have to use either the for loop or memcpy for initialization.
int arr1[10]={1,2,3,4,5};
// int arr2[10]=arr1;  This kind of initialization is not possible in c program

The char array can be initialized using the doble quotes. But it is not possible in the case of float and int.
char c[10]=”hello”;
// int i[10]=”12345”; Not possible for int,float

The array can be explicitly initialized using the above format. In case of int the remaining array will be initialized to zero. In case of char strlen returns zero if the first element of the array was not initialized.
int array[10]={[2]=2,[5]=1};
char c[10]={[2]=’a’,[3]=’d’};//strlen(c) is zero.

The above will initialize the 1st element of array to empty space. In similar fashion if you leave two spaces then the first two index will be initialized to empty space.
char c[10]=” “;

The two array cannot be intialized without mentioning the size at both the dimensons. But you can intialize by without specifying the 1st dimenson.

int arr[]={12,5,8} // This is valid in c and c++
int arr[][]={{1,3},{2,5}}; // Not valid in c and c++
int arr[][10]={{1,3},{2,5}}; //  valid in c and c++




IMG SRC: http://www.mattababy.org/~belmonte/Teaching/CCC/CrashCourseC.html
Tag name in struct is one which is the name of the struct we are giving while creating the struct. For instance, in the following declaration

struct s
{
---
}var;

s is the tag name. Some will misunderstood s as type name. Here s  is not a type name they are actually tag names. They are also like a normal identifiers in c.

The following usage is wrong in c code,
s var1;   // Wrong Declaration
struct s var1; //Correct Declaration

Although they are name of the structures we cannot create the variable by just calling them. You need to use the struct keyword while using that identifier.

The process of calling the struct s var1 is called as elaborated type specifier.
The enums, union also fall under same category. The name of the enum or union cannot be used separately, they have called with their keywords such as struct, enum;

WHY TYPEDEF IS GIVEN OFTEN IN STRUCT:
You will wonder sometimes, that why programmers always use a typedef in the struct keyword. This is because, writing
struct s
{
--
};
struct s member1;
is equal to
typedef struct  s
{
--
}s_ref;
s_ref member1;

If we fail to use the typedef and in order to use the struct in future, we need to specify struct keyword often. So we are using the typedef in struct programs.

NORMAL IDENTIFIERS AND TAG NAMES:

The normal identifiers cannot be used like this
int flag;
void flag();

Compiler throws error at second declaration. But in family that uses the tag names  can have the same name as identifier.
struct s {};  //valid
enum s{};    //valid
union s{};    //valid

This is because they are referred using the keyword. C stores this identifier in a different table.
And even the following cases also is valid

int s;
struct s{};

1.USE OF elaborated type specifier:
In C, it is compulsory to use a elaborated type specifier for using the struct, union, and enums.
So are you wonder what is elaborated type specifier am I correct?

ELABORATED TYPE SPECIFIER:

While creating the object for the struct , you need to use a struct keyword along with the type name. (strcut s obj;) here struct is keyword s is typename obj is object. This process of creating the object using type name and their corresponding keyword is called as elaborated type specifier.
i.e, we cannot use like following,
struct s
{
---;
}
s obj;// Invalid in c, but valid in c++

Finally, In C we have to use ( struct s {} as struct s obj; ) and in c++ (s obj; )But using elaborated type specifier is also valid in c++.(struct s obj)


In similar to the above discussion, in c++ we are using class c{} as c obj;

Thursday, 16 January 2014

1.CREATING THE OBJECT WITHOUT NEW:

myclass obj;
This creates the object for the myclass. This is similar to initializing the variable (int a;). Here myclass is the type name and obj is variable. This is static storage duration and uses the stack memory. Here the scope of the variable obj expired at the end of the block. 

2. CREATING THE POINTER TO CLASS:

myclass *obj;
This is the  pointer to class. i.e., we have created obj Pointer to myclass. you can initialize the obj in two ways
Method 1:
This is static method. This kind is passing a address of one object to initialize the pointer object.
myclass obj1,*obj2;
obj2=&obj1; //static allocation and  calls the constructor with no arguments
Method 2:
This is dynamic method. This creates a dynamic memory and need to be removed explicitly otherwise the memory leak will occur. 
myclass obj1,*obj2;
obj2=new obj1;  //Dynamic allocation and  calls the constructor with no arguments
………..
delete obj2;

3.INVALID USE OF NEW OPERATOR:
myclass obj=new myclass;
This is wrong method of creating the object. If you want to use this signature, then the obj should be a pointer to the object.

4.DIFFERENCE BETWEEN GIVING CLASS NAME AND FUNTION AFTER NEW OPERATOR:

myclass *obj=new myclass;  //Type1
myclass *obj=new myclass();  //Type2

Both are same. If we fail to give the paranthesis then the compiler will take it as  an constructor with no parameter.

5.USING NEW OPERATOR FOR BASIC DATATYPE:

int *a;
a=new int(5);
Here the memory for a is created at run time, and the a is initialized with value of 5 at runtime. a is stored under the heap memory and a is to be deallocated explicitly.

6.HEAP MEMORY AND STATIC MEMORY:

Heap memory for the dynamic memory allocation.
Stack memory is for the static memory allocation.




#include<iostream>
using namespace std;

class new_demo
{

};

int main()
{
   cout<<"Creating Object without new!!!\n";
   new_demo obj1;

   cout<<"Creating a pointer to class\n";
   new_demo *obj_pointer;

   cout<<"Assigning a pointer to class with obj1\n";
   obj_pointer=&obj1;

   cout<<"Creating a object with new operator \n";
   obj_pointer=new new_demo;

   cout<<"Wrong: Creating a object with new operator and assigning to a normal object instead of pointer \n";
   // obj1=new new_demo;  Obj is object here we cannot use new for that

   return 0;

}

Output:

Creating Object without new!!!
Creating a pointer to class
Assigning a pointer to class with obj1
Creating a object with new operator
Wrong: Creating a object with new operator and assigning to a normal object instead of pointer

Wednesday, 8 January 2014

Reference is used in c++ to create a alias for the variable. It is just used like a nick name. Consider you  have variable a, if you need to use the variable a as b, you can create a reference.
To create a reference append a ampersand symbol as prefix to variable at a time of creation. Don’t confuse with the ampersand symbol. It is not a symbol used for address reference here.
Consider the example

int a=5;
int a2=10;
int &b=a;
int &c; //Not valid need to initialize
int &d=NULL;  //not valid statement
int *p=NULL;
int e=p;  //not valid assigning NULL pointer
b=a2;  //not valid cannot initialize reference variable again

In above example, the alias name for a is created, it is b.
So here are some scenarios

cout<<a;  //prints 5
cout<<b;  //prints 5
b++;  //changes the value of a
cout<<a; //prints 6
cout<<b;  //prints 6

Datatype conflict:
You cannot make a reference for the different data types  For Eg you cannot refer a integer variable to the double reference.

int a;
int &b=a;  /valid assignment
double &c=a;   //invalid assignment

pointer vs references:

The pointer and reference are almost same with some of the following differences.
1.      You can assign a NULL value to pointer, but you cannot do that in reference.
2.      Pointer can be reassigned many number of times, but in a reference we cannot do that. Reference can be initialized only once.
3.      Reference must be initialized at the time of declaration.  But pointers can be initialized any number of time.
4.      If pointer is incremented it will point to next memory address, whereas if reference is incremented the variable that reference is pointing to will be incremented.

Although, reference seems to be different concept, Probably it is internally treated as a pointers by the compiler.  Some other compilers will treat it as alias.