Proc C: Stored procedure call is not at all calling - oracle-pro-c

Below SQL code is not at yet all executing. Not sure why?
printf("id value: %s \n" ,Id);
EXEC SQL WHENEVER NOT FOUND CONTINUE;
EXEC SQL at DB_NAME EXECUTE
BEGIN
PACK.get_data(:Id, :intSQLCode, :intSQLCount, :fund_cursor);
END;
END-EXEC;
printf( " from SP: %d \n", intSQLCode);
printf(lmsg, "from SP: %d \n", intSQLCount);
GetRowCnt = intSQLCount;
if (GetRowCnt == 0)
{
GetRowCnt = 9;
}
if (sqlca.sqlcode != 0)
{
printf("call failed - SQL Code:%d \n",
(int)sqlca.sqlcode);
intReturn = sqlca.sqlcode;
return (intReturn);
}
if (intSQLCode != 0)
{
printf("returned failure code:%d \n",intSQLCode);
intReturn = intSQLCode;
return(intReturn);
}
From the above code: First line of code Id value printf line is executing and it's printing the ID value : FIRST
After that none of the code is not executing means, i'm not seeing any errors/any printf statements which are there in error handling.
I wrote the same code in sample program to test, it's executing and everything is fine. But in application same code is not executing and not printing anything.

Related

Need an Oracle Pro*C program that queries for all of a user's tables

I'm new to Pro-C and Oracle (but not databases) so I probably need some fundamental help on what I'm doing wrong. I wrote the following Pro*C program to query for all the tables owned by a specific user:
#include <stdio.h>
EXEC SQL INCLUDE SQLCA;
int main() {
int i;
char oraCreds[10] = "user/pass";
char tables[50][50], parts[50][50];
exec sql connect :oraCreds;
if (sqlca.sqlcode != 0) {
printf("ERROR abbreviated\n");
return(0);
}
EXEC SQL SELECT TABLE_NAME
INTO :tables
FROM USER_TABLES;
if (sqlca.sqlcode != 0) {
printf("ERROR: Could not query database for user tables\n");
printf("\tError Code: %d\n", sqlca.sqlcode);
printf("\t%.*s\n", sqlca.sqlerrm.sqlerrml, sqlca.sqlerrm.sqlerrmc);
} else {
for (i = 0; i < 50; i++) {
printf("\nTable %d: %s\n", i+1, tables[i]);
}
}
// Code below inserted here
return(0);
}
This produces the following error:
ERROR: Could not query database for user tables
Error Code: 1403
ORA-01403: no data found
The problem is that there are records in user_tables and in sqlplus I can do a typical SELECT TABLE_NAME FROM USER_TABLES; in order to verify that.
In an attempt to verify some of the basic functionality of above program, I inserted the following query at the comment.
EXEC SQL SELECT NAME, PART_NO
INTO :tables, :parts
FROM ITEMS;
if (sqlca.sqlcode != 0) {
printf("ERROR: Could not query database for user tables\n");
printf("\tError Code: %d\n", sqlca.sqlcode);
printf("\t%.*s\n", sqlca.sqlerrm.sqlerrml, sqlca.sqlerrm.sqlerrmc);
} else {
for (i = 0; i < 50; i++) {
printf("\nTable %d: %s\n", i+1, tables[i]);
}
}
This second query gives the expected results and prints out one line for each item's name.
If I understand correctly, the table, user_tables, is a standard part of Oracle, so is there something special about it that would be throwing off my query? I've started reading some alternate ways to query for the user's tables, but I would love to know why the above method does not work.

unable to add columns to a existing table using C

The following program tries to insert a new row and a new column to an already existing database with a table "people" containing four cols (id, lastname, firstname, phonenumber). While the row gets inserted successfully, the column is not getting added.
#include <stdio.h>
#include <stdlib.h>
#include <libpq-fe.h>
#include <string.h>
int main()
{
PGconn *conn;
PGresult *res;
int rec_count;
int row;
int col;
conn = PQconnectdb("dbname=test host=localhost user=abc1 password=xyz1");
if(PQstatus(conn) == CONNECTION_BAD) {
puts("We were unable to connect to the database");
exit(0);
}
res = PQexec(conn,"INSERT INTO people VALUES (5, 'XXX', 'YYY', '7633839276');");
if(PQresultStatus(res) != PGRES_COMMAND_OK) {
fprintf(stderr, "Insertion Failed1: %s", PQerrorMessage(conn));
PQclear(res);
}
else
printf("Successfully inserted value in Table..... \n");
res = PQexec(conn,"update people set phonenumber=\'5055559999\' where id=3");
if(PQresultStatus(res) != PGRES_COMMAND_OK) {
fprintf(stderr, "Insertion Failed2: %s", PQerrorMessage(conn));
PQclear(res);
}
res = PQexec(conn, "ALTER TABLE people ADD comment VARCHAR(100) DEFAULT 'TRUE'");
if(PQresultStatus(res) != PGRES_COMMAND_OK) {
fprintf(stderr, "Insertion Failed3: %s", PQerrorMessage(conn));
PQclear(res);
}
rec_count = PQntuples(res);
printf("We received %d records.\n", rec_count);
puts("==========================");
for(row=0; row<rec_count; row++) {
for(col=0; col<3; col++) {
printf("%s\t", PQgetvalue(res, row, col));
}
puts("");
}
puts("==========================");
PQclear(res);
PQfinish(conn);
return 0;
}
The program after being compiled and linked gives the following output:
$ ./test
Successfully inserted value in Table.....
We received 0 records.
==========================
==========================
In the postgresql environment, the table "people" is updated with an extra row and a column containing "TRUE".
This is my first program with C embedded with postgresql. Please help!!
This line:
res = PQexec(conn, "EXEC('UPDATE people SET comment = ''TRUE'';');");
should be:
res = PQexec(conn, "UPDATE people SET comment = 'TRUE'");
The EXEC syntax is part of embedded SQL in C with ECPG. It's not to be combined with PQexec from the C libpq library, which is clearly what you're using given the rest of the source code.
Also the result of an UPDATE with no RETURNING clause has PQresultStatus(res)==PGRES_COMMAND_OK, not PGRES_TUPLES_OK
PGRES_COMMAND_OK
Successful completion of a command returning no data.
See Command Execution Functions
You also want to test any PGresult returned by PQexec, not only the result of your last query, because any query may fail.
How can you retrieve data without doing a SELECT statement ?
Never used PQexec, but i guess the code to add might be like this:
res = PQexec(conn, "ALTER TABLE people ADD comment VARCHAR(100) DEFAULT 'TRUE'");
if(PQresultStatus(res) != PGRES_COMMAND_OK) {
fprintf(stderr, "Insertion Failed3: %s", PQerrorMessage(conn));
PQclear(res);
}
//Add PQexec and select statement here.
//Something "like" this.
res = PQexec(conn, "SELECT * FROM people;");
if(PQresultStatus(res) != PGRES_TUPLES_OK) {
fprintf(stderr, "Select Failed: %s", PQerrorMessage(conn));
PQclear(res);
}
rec_count = PQntuples(res);
printf("We received %d records.\n", rec_count);

Pro*C Oracle -- looping through sql fetch

I'm beginning with Pro*C and have a program that reads in records and prints out grouped by an identifying value (guests). In order to get all the information printed, I used a break from the for loop to control what goes where. It compiles but it's not following the printing scheme and actually goes into an infinite loop. The last break at the end is to stop the infinite loop, and it's not hitting any of the conditionals for some reason (even with a default else). There's limited debugging on the remote database server it's executing on (dbx is not available).
While not end of cursor (ie. sqlcode = 0)
If PrevSaleItem Not = Cursor.Item_ID
Write The Subtotals for the Item
Initialize ItemQty and ItemTotal to 0
Set PrevSaleItem to Cursor.Item_ID
End if
Print Out Detail Line
Add Cursor.Quantity to ItemQty
Add Cursor.calc_tax to ItemTotal and GuestTotal
Fetch next record in cursor
End While
Print the Subtotals for the last item
Print the Grand totals
exec sql open dbGuest;
exec sql fetch dbGuest into :sLastName, :sFirstName, :nItemID, :sItemName, :nQuantity, :nUnitPrice, :sTransDate, :sHotelName, :nHotelID, :sTaxable, :nCalcTax;
/* Lets check the status of the OPEN statement before proceeding , else exceptions would be suppressed */
if(sqlca.sqlcode !=0) // If anything went wrong or we read past eof, stop the loop
{
printf("Error while opening Cursor <%d><%s>\n",sqlca.sqlcode,sqlca.sqlerrm.sqlerrmc);
break;
}
int PrevSaleItem = 0;
int ItemQty = 0;
double ItemTotal = 0.0;
double GuestTotal = 0.0;
for(;;)
{
printf("%s %s %s %s %d\n","Charge Summary for:", sFirstName.arr, sLastName.arr, " Guest_ID:", nGuest_ID);
printf("%s %d %s %s \n", "Sales_Item: ", nItemID, " - ", sItemName.arr);
// Do the crazy stuff to end the C-Strings
sLastName.arr[sLastName.len] = 0;
sFirstName.arr[sFirstName.len] = 0;
sItemName.arr[sItemName.len] = 0;
sTransDate.arr[sTransDate.len] = 0;
sHotelName.arr[sHotelName.len] = 0;
sTaxable.arr[sTaxable.len] = 0;
// initialize
PrevSaleItem = nItemID;
ItemQty = 0;
ItemTotal = 0.0;
GuestTotal = 0.0;
//While not end of cursor (ie. sqlcode = 0)
/* Check for No DATA FOUND */
if (sqlca.sqlcode == 0)
{
if(PrevSaleItem != nItemID)
{
printf("ItemQty: %f \t ItemTotal: %f",ItemQty,ItemTotal);
ItemTotal = 0.0;
GuestTotal = 0.0;
PrevSaleItem = nItemID;
}
printf("GuestTotal \t\t %f",GuestTotal);
ItemQty += nQuantity;
ItemTotal += nCalcTax;
GuestTotal += nCalcTax;
}
else if(sqlca.sqlcode == 100 || sqlca.sqlcode == 1403) // If anything went wrong or we read past eof, stop the loop
{
printf("CURSOR is empty after all fetch");
PrevSaleItem = -1;
break;
}
/* Check for other errors */
else if(sqlca.sqlcode != 0)
{
printf("Error while fetching from Cursor <%d><%s>\n",sqlca.sqlcode,sqlca.sqlerrm.sqlerrmc);
break;
}
else {printf("HIT ELSE"); break;}
break;
}
// close the cursor and end the program
exec sql close dbGuest ;
The logic that should be happening is as follows:
Assume the break mechanism is within an outer for loop (not shown). It should open the cursor, fetch the 1st record, and then print the heading for the guest and the sales item. It then initializes the totals and break variables by setting the values. While not the end of cursor (sqlcode is 0, and instead of while just used for loop with break) if the previous item != the item id then it prints subtotals, initializes item quantities and totals to 0 and sets the previous item to item id (then breaks the if conditional). Item quantity is increased by the quantity in the table, and the calc_tax is added to the item and guest totals. The next record is fetched, the totals for that last item are printed, and then the grand totals for that guest are printed.
It's not printing the amounts where it should be and is in infinite loop, and after I tried breaks in all the conditionals, I'm at a loss to explain how it's happening. I'm sure it's a beginner mistake, so maybe a jr Oracle developer (but a pro would be great) has a moment to get me back on track here.
Your fetch is outside the for loop. You go into the loop after the first fetch. If sqlca.sqlcode is zero after that first fetch, it isn't reaching any of the breaks because of the nested if and else, so it goes round the loop again. Becuase there is not a second fetch, you still have a good sqlcode, so it keeps going. I think.... Anyway, moving your fetch into the loop looks like what you want to happen?
It does look like that final break should kick in, but yesterday you posted code you'd modified so I'm not sure if that's the case here too.
If you reformat your code and introduce braces and nesting for the else conditions you can see they don't line up. The final { you showed isn't for the for, it's for one of the branches.
for(;;)
{
if (sqlca.sqlcode == 0)
{
if(PrevSaleItem != nItemID)
{
...
}
....
}
else
{
if(sqlca.sqlcode == 100 || sqlca.sqlcode == 1403)
{
break;
}
else
{
if(sqlca.sqlcode != 0)
{
break;
}
else
{
printf("HIT ELSE");
break;
}
break;
}
// close the cursor and end the program
exec sql close dbGuest ;
The else if(sqlca.sqlcode != 0) is redundant; at this point sqlca.sqlcode has to be something other than 0, 100 or 1403. So it can't reach the next else either.

Oracle Pro*C updating table with cursor failed

I have a table like this:
CREATE TABLE book_info (
book_id VARCHAR(32) not null,
title varchar(255) not null,
author varchar(255) not null,
folder_path varchar(255) not null,
primary key(book_id)
);
And i insert this data on it:
insert into book_info values('BOOK1', 'APUE', 'Richard Stevens', '/home/user1/unix_programming_books');
insert into book_info values('BOOK2', 'Unix Network programming', 'Richard Stevens', '/home/user1/unix_programming_books');
insert into book_info values('BOOK3', 'Core Python Applications Programming', 'Wesley J. Chun', '/home/user1/python_programming_books');
I'm trying to update this table using Oracle PRO*C, but i can't! below is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
EXEC SQL INCLUDE SQLCA;
EXEC SQL INCLUDE ORACA;
#define USER_LEN 10
#define PASS_LEN 10
VARCHAR user[USER_LEN];
VARCHAR pass[PASS_LEN];
#define STRCPY_TO_ORA(dest, source)\
dest.len = strlen(source);\
strcpy((char *)dest.arr, (const char *)source)
#define STRCPY_FROM_ORA(dest, source)\
source.arr[source.len] = 0;\
strcpy((char *)dest,(const char *)source.arr)
/* Connecting to the database */
int db_connection(char *db_user, char *db_pass)
{
strncpy((char *) user.arr, db_user, USER_LEN);
user.len = strlen((char *) user.arr);
strncpy((char *) pass.arr, db_pass, PASS_LEN);
pass.len = strlen((char *) pass.arr);
EXEC SQL CONNECT :user IDENTIFIED BY :pass;
if (sqlca.sqlcode != 0)
{
fprintf(stdout, "Connection failed:%s\n", sqlca.sqlerrm.sqlerrmc);
return(sqlca.sqlcode);
}
fprintf(stdout, "Connected to ORACLE as user:%s\n", user.arr);
return (sqlca.sqlcode);
}
int book_not_found_function(char *path)
{
fprintf(stdout, "%s\n", __FUNCTION__);
}
int path_update_success_function(char *book_id, char *new_path)
{
fprintf(stdout, "Update book %s path to %s\n", book_id, new_path);
}
void other_function(void)
{
fprintf(stdout, "%s\n", __FUNCTION__);
}
/* Updating books path */
int books_path_updating(char *old_path, char *new_path)
{
char book_id_string[32];
EXEC SQL BEGIN DECLARE SECTION;
varchar sql_old_path[255];
varchar sql_new_path[255];
varchar sql_book_id[32];
EXEC SQL END DECLARE SECTION;
STRCPY_TO_ORA(sql_old_path, old_path);
STRCPY_TO_ORA(sql_new_path, new_path);
/* Declare a cursor for the FETCH statement. */
EXEC SQL DECLARE books_cursor CURSOR FOR
SELECT BOOK_ID
FROM BOOK_INFO
WHERE FOLDER_PATH = :sql_old_path;
if (sqlca.sqlcode != 0)
{
fprintf(stdout, "Declare cursor failed\n");
fprintf(stdout, "Oracle error %s\n", sqlca.sqlerrm.sqlerrmc);
return(sqlca.sqlcode);
}
EXEC SQL OPEN books_cursor;
if (sqlca.sqlcode != 0)
{
fprintf(stdout, "Open cursor failed\n");
fprintf(stdout, "Oracle error %s\n", sqlca.sqlerrm.sqlerrmc);
return(sqlca.sqlcode);
}
for ( ;; )
{
//EXEC SQL WHENEVER NOT FOUND DO break; // I used it but still nothing
//EXEC SQL WHENEVER NOT FOUND GOTO not_found; // I used this too
//EXEC SQL WHENEVER NOT FOUND DO continue; // I used this too
/* Fetching data */
EXEC SQL FETCH books_cursor
INTO :sql_book_id;
if (sqlca.sqlcode == 1403)
{
fprintf(stdout, "No book found for this folder %s\n", old_path);
book_not_found_function(old_path);
return 0;
}
else if (sqlca.sqlcode != 0)
{
fprintf(stdout, "Oracle error %s\n", sqlca.sqlerrm.sqlerrmc);
EXEC SQL CLOSE books_cursor;
return (sqlca.sqlcode);
}
else
{
STRCPY_FROM_ORA(book_id_string, sql_book_id);
fprintf(stdout, "BOOK_ID = %s\n", book_id_string);
/* Updating the path */
EXEC SQL UPDATE BOOK_INFO
SET FOLDER_PATH =:sql_new_path
WHERE BOOK_ID =:sql_book_id;
if (sqlca.sqlcode != 0)
{
fprintf(stdout, "Oracle error %s\n", sqlca.sqlerrm.sqlerrmc);
EXEC SQL CLOSE books_cursor;
return (sqlca.sqlcode);
}
else
{
path_update_success_function(book_id_string, new_path);
}
}
}
EXEC SQL CLOSE books_cursor;
other_function();
EXEC SQL COMMIT WORK RELEASE;
return 0;
}
int main(int argc, char **argv)
{
db_connection("evariste", "123456");
books_path_updating("/home/user1/unix_programming_books", "/home/user1/UNIX_PROGRAMMING_BOOKS");
books_path_updating("/non_existing_path", "/non_existing_path");
return 0;
}
This program produce the output :
Connected to ORACLE as user:evariste
BOOK_ID = BOOK1
Update book BOOK1 path to /home/user1/UNIX_PROGRAMMING_BOOKS
BOOK_ID = BOOK2
Update book BOOK2 path to /home/user1/UNIX_PROGRAMMING_BOOKS
No book found for this folder /home/user1/unix_programming_books // WHEY THIS?
book_not_found_function // WHY THIS
Declare cursor failed // WHY THIS
Oracle error ORA-01403: no data found // WHY THIS
The table is not updated and the functions path_update_success_function and other_function are never executed! Why this?
Thanks for your help.
Connected to ORACLE as user:evariste
BOOK_ID = BOOK1
Update book BOOK1 path to /home/user1/UNIX_PROGRAMMING_BOOKS
BOOK_ID = BOOK2
Update book BOOK2 path to /home/user1/UNIX_PROGRAMMING_BOOKS
No book found for this folder /home/user1/unix_programming_books // WHEY THIS?
You've fetched past the end of the resultset. Two rows match the cursor this time, so the first two fetches succeed; the third gets no data. This is expected and you shouldn't treat this as an error - just break the loop, which will also cause other_function to be called.
book_not_found_function // WHY THIS
Because you treat 1403 as an error. If you want to call this function when there are no matches, you'll need to count in the loop, and call it afterwards if needed.
Declare cursor failed   // WHY THIS
Oracle error ORA-01403: no data found // WHY THIS
sqlca.sqlcode seems to still be set from the earlier fetch, so this is misleading.
As far as I can remember you'd normally declare the cursor once in the file, not each time the function is called; not sure if Pro*C just ignores the redefinition. You can look at the generated file to see how it deals with it. You also won't get a runtime error from this, if it's wrong it won't (pre-)compile.
The table is not updated and the functions
path_update_success_function and other_function are never executed!
Why this?
path_update_success is called for the first two fetches, but not for the third which fails, and not for the second path because the function returns due to the apparent declare cursor before it gets near it. other_function isn't called because for both calls you return from the function before you can reach it. Similarly the table seems to not be updated because you return before you commit. Unlike SQL*Plus, Pro*C doesn't automatically commit on exit, so there is an implicit rollback. Note also that if you did get to the commit, the release disconnects you, so the second time you'd get a not-connected-to-Oracle error. You should decide to commit/rollback once really, probably right at the end of main.
Untested modification:
int books_path_updating(char *old_path, char *new_path)
{
char book_id_string[32];
int books_found;
EXEC SQL BEGIN DECLARE SECTION;
varchar sql_old_path[255];
varchar sql_new_path[255];
varchar sql_book_id[32];
EXEC SQL END DECLARE SECTION;
STRCPY_TO_ORA(sql_old_path, old_path);
STRCPY_TO_ORA(sql_new_path, new_path);
/* Declare a cursor for the FETCH statement */
EXEC SQL DECLARE books_cursor CURSOR FOR
SELECT BOOK_ID
FROM BOOK_INFO
WHERE FOLDER_PATH = :sql_old_path;
EXEC SQL OPEN books_cursor;
if (sqlca.sqlcode != 0)
{
fprintf(stdout, "Open cursor failed\n");
}
books_found = 0;
while (sqlca.sqlcode == 0)
{
/* Fetching data */
EXEC SQL FETCH books_cursor
INTO :sql_book_id;
if (sqlca.sqlcode != 0)
{
break;
}
STRCPY_FROM_ORA(book_id_string, sql_book_id);
fprintf(stdout, "BOOK_ID = %s\n", book_id_string);
/* Updating the path */
EXEC SQL UPDATE BOOK_INFO
SET FOLDER_PATH = :sql_new_path
WHERE BOOK_ID = :sql_book_id;
if (sqlca.sqlcode != 0)
{
break;
}
/* Track how many books we found, though we only really care later that
* this is non-zero */
books_found++;
path_update_success_function(book_id_string, new_path);
}
EXEC SQL CLOSE books_cursor;
/* Check for and display error, but ignore 1403 as this just indicates the
* end of the result set */
if ((sqlca.sqlcode != 0) && (sqlca.sqlcode != 1403))
{
fprintf(stdout, "Oracle error %s\n", sqlca.sqlerrm.sqlerrmc);
return 1;
}
if (books_found == 0)
{
fprintf(stdout, "No book found for this folder %s\n", old_path);
book_not_found_function(old_path);
return 0;
}
other_function();
return 0;
}
int main(int argc, char **argv)
{
int rc;
rc = db_connection("evariste", "123456");
/* Only do the first path if we didn't get an error connecting */
if (rc == 0)
{
rc == books_path_updating("/home/user1/unix_programming_books",
"/home/user1/UNIX_PROGRAMMING_BOOKS");
}
/* Only do the next path if we didn't get an error from the previous one */
if (rc == 0)
{
rc = books_path_updating("/non_existing_path",
"/non_existing_path");
}
/* Decide whether to rollback or commit; this assumes you don't want to
* keep any changes if there are any errors */
if (rc != 0)
{
EXEC SQL ROLLBACK WORK RELEASE;
return 1;
}
EXEC SQL COMMIT WORK RELEASE;
return 0;
}
Seems DECLARE CURSOR does not set sqlca.sqlcode.
The error you've got was the previous one when you achieved the end of your fetch.
So you should not test errors after a DECLARE CURSOR, but after the OPEN CURSOR only.

Unix C code cp in system()

I have a C code..
i which I have following code for UNIX:
l_iRet = system( "/bin/cp -p g_acOutputLogName g_acOutPutFilePath");
when I am running the binary generated..I am getting the following error:
cp: cannot access g_acOutputLogName
Can any one help me out?
You should generally prefer the exec family of functions over the system function. The system function passes the command to the shell which means that you need to worry about command injection and accidental parameter expansion. The way to call a subprocess using exec is as follows:
pid_t child;
child = fork();
if (child == -1) {
perror("Could not fork");
exit(EXIT_FAILURE);
} else if (child == 0) {
execlp("/bin/cp", g_acOutputLogName, g_acOutPutFilePath, NULL);
perror("Could not exec");
exit(EXIT_FAILURE);
} else {
int childstatus;
if (waitpid(child, &childstatus, 0) == -1) {
perror("Wait failed");
}
if (!(WIFEXITED(childstatus) && WEXITSTATUS(childstatus) == EXIT_SUCCESS)) {
printf("Copy failed\n");
}
}
Presumably g_acOutputLogName and g_acOutPutFilePath are char[] (or char*) variables in your program, rather than the actual paths involved.
You need to use the values stored therein, rather than the variable names, for example:
char command[512];
snprintf( command, sizeof command, "/bin/cp -p %s %s",
g_acOutputLogName, g_acOutPutFilePath );
l_iRet = system( command );