The following code connects to the database and then performs some operations
The name of my database table is ym_test. There are only two fields, int type I, and char * type
Dbop. PC File
- # Include <stdio. h>
- # Include <stdlib. h>
- # Include <string. h>
- # Include "dbop. H"
- Exec SQL begin declare section;
- SQL _context CTX;
- Exec SQL end declare section;
- Exec SQL include sqlca;
- Void sqlerror ();
- Int conndb (char * sdbconnstr)
- {
- Exec SQL begin declare section;
- Char sconnsql [256];
- Exec SQL end declare section;
- Memset (sconnsql, 0, sizeof (sconnsql ));
- Snprintf (sconnsql, sizeof (sconnsql), "% s", sdbconnstr );
- Exec SQL context allocate: CTX;
- Exec SQL context use: CTX;
- Exec SQL CONNECT: sconnsql;
- Return sqlca. sqlcode;
- }
- Int releasedb ()
- {
- Exec SQL commit release;
- Return 0;
- }
- Int readdb (INT number)
- {
- Exec SQL begin declare section;
- Int num;
- Char name [20];
- Exec SQL end declare section;
- Num = number;
- Exec SQL select Str
- Into: Name
- From ym_test
- Where I =: num;
- Printf ("/n % s/n", name );
- Return 0;
- }
- Int writedb (INT number, char * names)
- {
- Exec SQL begin declare section;
- Int num;
- Char name [20];
- Exec SQL end declare section;
- Num = number;
- Strcpy (name, names );
- Exec SQL insert
- Into ym_test (
- I,
- Str
- ) Values (
- : Num,
- : Name
- );
- Return 0;
- }
- Int deletedb (INT number)
- {
- Exec SQL begin declare section;
- Int num;
- Exec SQL end declare section;
- Num = number;
- Exec SQL Delete from ym_test
- Where I =: num;
- Return 0;
- }
- Void sqlerror ()
- {
- Exec SQL whenever sqlerror continue;
- Printf ("/noracle error detected:/N ");
- Printf ("% d/N", sqlca. sqlcode );
- Printf ("/n % s/n", sqlca. sqlerrm. sqlerrmc );
- /* Roll back the transaction */
- Exec SQL rollback release;
- Exit (1 );
- }
The main. cpp file code is as follows:
- # Include <stdio. h>
- # Include <stdlib. h>
- # Include <string. h>
- # Include "dbop. H"
- Int main (INT argc, char * argv [])
- {
- Conndb (user01/user001 @ testdb );
- Readdb (2 );
- Readdb (1 );
- Writedb (22, "mengge ");
- Readdb (22 );
- Deletedb (2 );
- Releasedb ();
- Return 0;
- }
The compilation script is:
- #! /Bin/sh
- Proc code = CPP ltype = none INAME = dbop. PC oname = dbop. cpp
- G ++-g-wall-C dbop. cpp
- G ++-g-wall-C main. cpp
- G ++-g-wall-L $ ORACLE_HOME/lib-l clntsh main. O dbop. O-o main
- # Deleting intermediate files
- Rm-F dbop. O dbop. cpp main. o