unable to add columns to a existing table using C - sql

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);

Related

How to get the name of the last column from the SQL table without traversing in SQLite3?

My database contains 'n' number of columns.
For example:
Name city phone number ..............,
Exactly I don't know about the total number of columns and name of the last column.
The name of the columns will be changed at run time (such as The name of columns are not constant fields).
#include <stdio.h> /* needed for vsnprintf */
#include <stdlib.h> /* needed for malloc-free */
#include <string.h>
#include <sqlite3.h>
char * sql = PRAGMA table_info(table_name);
int i = 0;
rc = sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, NULL);
printf(" PRAGMA: rc = %d\n", rc);
if(rc != SQLITE_OK )
{
printf("Error: %s:Unable to Query the SQL Column from the table.\n", zErrMsg);
}
else if(rc == SQLITE_OK)
{
while(sqlite3_step(stmt) == SQLITE_ROW)
{
int totCol = sqlite3_column_count(stmt);
for(i=0; i<totCol ;i++)
{
printf("Column-Name: %s\n", sqlite3_column_text(stmt, i));
}
}
}
Through the above pragma command, I am traversing the entire columns in the SQL table and found the name of the last column.
Is there any way to know the name of the last column without traversing the entire columns in the SQL table.
Note: I don't want to do the following things
Executing more than one SQL statement.
Traversing the entire columns to find the last column from the SQL table.
I believe that you can achieve this using the following as the basis :-
SELECT name FROM pragma_table_info('table_name') ORDER BY cid DESC LIMIT 1;
As described in PRAGMA Statements - PRAGMA functions

Unable to add list to the record

I'm trying to add a record to the database having 3 bins, one of which is a list using my c++ program(I'm using Aerospike's C client library) but after I execute my program, only 2 of the bins are added in the record. For some reasons, I'm not able to add the 3rd bin having the list value.
Given below is the program:
#include<aerospike/aerospike.h>
#include<aerospike/as_arraylist.h>
#include <aerospike/as_record.h>
#include<aerospike/as_record_iterator.h>
#include <aerospike/as_policy.h>
#include<aerospike/aerospike_key.h>
#include<aerospike/as_std.h>
#include<aerospike/as_integer.h>
#include<aerospike/as_string.h>
#include<iostream>
#include<aerospike/as_hashmap.h>
#include<string>
using namespace std;
int main()
{
as_error err;
as_config config;
as_config_init(&config);
config.policies.write.key = AS_POLICY_KEY_SEND;
as_config_add_host(&config, "182.18.182.192", 3000);
aerospike as;
aerospike_init(&as, &config);
if(aerospike_connect(&as, &err)!=AEROSPIKE_OK)
{
printf("error(%d) %s at [%s:%d]", err.code, err.message, err.file, err.line);
}
as_key key;
as_record rec;
as_record_init(&rec, 2);
int n;
cout<<endl<<"Enter the number of records to enter: ";
cin>>n;
for(int i=0;i<n;i++)
{
cout<<endl<<"Enter the name: ";
string pk;
getline(cin>>ws,pk);
as_key_init(&key, "test", "vishal_set", pk.c_str());
cout<<endl<<"Enter the age: ";
int age;
cin>>age;
as_record_set_int64(&rec, "age", age);
cout<<endl<<"Enter the contact no: ";
string contact_no;
getline(cin>>ws,contact_no);
as_record_set_str(&rec, "contact_no", contact_no.c_str());
as_arraylist list;
as_arraylist_inita(&list,2);
as_arraylist_append_str (&list, "playing football");
as_arraylist_append_str (&list, "playing cricket");
cout<<endl<<"Number of elements in the list: "<<as_arraylist_size(&list)<<endl;
if(!(as_record_set_list(&rec, "hobbies", (as_list *)&list)))
{
printf("\n[%s::%d]Error\n",__FILE__,__LINE__);
}
if (aerospike_key_put(&as, &err,NULL, &key, &rec) != AEROSPIKE_OK)
{
printf("error(%d) %s at [%s:%d]", err.code, err.message, err.file, err.line);
}
}
if(aerospike_close(&as,&err)!=AEROSPIKE_OK)
{
printf("error(%d) %s at [%s:%d]", err.code, err.message, err.file, err.line);
}
aerospike_destroy(&as);
return 0;
}
Fortunately, I've found the reason why my list was not getting added to the record myself. It turned out to be really silly mistake.
The reason was that I had done a mistake in initializing as_record. Since I was adding 3 bins to the record therefore, I should have initialised it as as_record_init(&rec, 3);.

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.

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.

Nothing is extracted from the SQlite table?

void max_min(sqlite3 *db)
{
//call back*********
int i, ncols;
sqlite3_stmt *stmt;
char *sql;
const char *tail;
char *zErrMsg = 0;
int rc;
//******************
//min/max variables
char min[20];
char max[20];
//we want only the min and max value of this table
sql = "SELECT MIN(Start),MAX(End)FROM GMTI;"; //doesn't extract but works in GUI tool?
//sql = "SELECT * FROM GMTI WHERE Start<16;"; //works?
rc = sqlite3_prepare(db, sql, strlen(sql), &stmt, &tail);
if(rc != SQLITE_OK){
fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
}
rc = sqlite3_step(stmt);
ncols = sqlite3_column_count(stmt);
printf("Number of columns: %d and row status: %d", ncols, rc);
while(rc == SQLITE_ROW){
for(i=0; i<ncols; i++){
if (strncmp("Start", sqlite3_column_name(stmt,i), strlen("Start")) == 0)
{
strncpy(min, sqlite3_column_text(stmt,i), strlen(sqlite3_column_text(stmt,i)));
strcpy(min + strlen(sqlite3_column_text(stmt,i)), "\0");
printf("min is: %s\n", min);
printf("<br>");
}
if (strncmp("End", sqlite3_column_name(stmt,i), strlen("End")) == 0)
{
strncpy(max, sqlite3_column_text(stmt,i), strlen(sqlite3_column_text(stmt,i)));
strcpy(max + strlen(sqlite3_column_text(stmt,i)), "\0");
printf("max: %s\n", max);
printf("<br>");
}
}//end for
fprintf(stderr, "\n");
rc = sqlite3_step(stmt);
}//end while
sqlite3_finalize(stmt);
}
When I use the sql query above with the MIN and MAX functions, nothing prints out for min and max. If I use one of the other statements commented out there, it works as expected, printing the selected query.
What is different about the max and min in the query, that it can't extract the values? Is it not in table format?
Also, I tested the problem query string in an SqLite database browser on the same database and it works, displaying the two - min and max values.
Any suggestions would be greatly appreciated.
Thanks.
Try printing out the returned column names. Maybe they don't equal "Start" and "End" as you assumed?
Maybe you should add a space between MAX(End) and FROM ?