Re: C und DB2


[ ruban.de ] [ Antworten ] [ Forum ]

Geschrieben von Bunbury on November 21, 2002 um 20:20:

Als Antwort auf C und DB2 geschrieben von Sven Schneider on November 21, 2002 um 13:25:

Hi Sven,

mit Hilfe von Embedded SQL kann man von C aus auf DB2-Tabellen zugreifen (SELECT, UPDATE, DELETE, INSERT, etc).

Falls das Anwendungsprogramm auf einer anderen Hardwareplattform läuft als die Datenbank selbst, benötigst Du noch eine passende Middleware, wie z. B. DB2 Connect, die die Verbindung herstellt.

Nachfolgend noch ein kleines Beispielprogrämmchen in C mit SQL.

Viel Glück
Bunbury


/***** Sample Application program #1 *****/
/********************************************************************
* SAMPLE PROGRAM: example1.sqc
*
* PURPOSE: This sample program demonstrates the use of embedded SQL
* in DB2. The program makes use of CURSOR to manage the
* query output. Assuming the following table in our database,
* the program retrieves all video titles.
*
* create table video(video_id int not null, \
* video_title varchar(30), \
* director varchar(20), \
* primary key(video_id))
*
********************************************************************/

#include

/* sqlca: is the sql communications area. All error codes
are returned from db2 in that structure which is filled
each time an interaction with db2 takes place.

*************************************
* No error : sqlca.sqlcode = 0 *
* SQL warning : sqlca.sqlcode > 0 *
* SQL error : sqlca.sqlcode < 0 *
* not found : sqlca.sqlcode = 100 *
*************************************
*/

EXEC SQL INCLUDE SQLCA; /* SQL communication area structure */

EXEC SQL BEGIN DECLARE SECTION; /* declare host variables */
char db_name[8]; /* database name */
char video_title[30]; /* title of the video */
short video_id; /* serial number */
char director[20]; /* director name */
EXEC SQL END DECLARE SECTION;

void main() {

strcpy(db_name, "csc2509h");

/* C variables are preceded by a colon when they are passed to DB2 */

EXEC SQL CONNECT TO :db_name;

if (sqlca.sqlcode != 0) {
printf("Connect failed!: reason %ld\n", sqlca.sqlcode);
exit(1);
}

/* cursor declaration. Have to declare a cursor each time you
want tuples back from db2
*/

EXEC SQL DECLARE c1 CURSOR FOR
SELECT video_title
FROM video;

/* you have to open the cursor in order to get tuples back */

EXEC SQL OPEN c1;

do {

/* fetch tuples from the cursor. This will execute the statement
the cursor implements and will return the results */

EXEC SQL FETCH c1 into :video_title;
if (SQLCODE != 0) break; /* SQLCODE refers to sqlca.sqlcode */

/* host variables should have ':' prefix when they are used in DB2 commands */

printf("%s\n",video_title);

} while (1);
EXEC SQL CLOSE c1;
EXEC SQL CONNECT RESET;
}




Antworten:


Schreibe eine Antwort

Name:   
E-Mail:  

Thema:

Kommentar:

Optionale Link URL:   
Link Titel:                  
Optionale Image URL:


[ Antworten ] [ Forum ]