I am a newbie in using libpq and work on a postgresql database.
So, far I can insert/update/etc a postgresql database using C program, provided I give the actual values inside the quotes.
I want to know how to pass a string/integer variable in the command??
E.g. The following code adds a column called "comment" containing "TRUE" default value into an existing table "people". I need to update the value of the "comment" by "FALSE" where the id=2.
#include <stdio.h>
#include <stdlib.h>
#include <libpq-fe.h>
#include <string.h>
void exit_nicely(PGconn *conn)
{
PQfinish(conn);
exit(1);
}
int main()
{
PGconn *conn;
PGresult *res;
int nFields;
int row_count=0,col_count=0;
int row=0;
int col=0;
conn = PQconnectdb("dbname=test host=localhost user=postgres password=xxx");
if(PQstatus(conn) == CONNECTION_BAD)
{
fprintf(stderr, "Connection to database \"%s\" failed.\n", PQerrorMessage(conn));
fprintf(stderr, "%s", PQerrorMessage(conn));
exit_nicely(conn);
}
res = PQexec(conn, "ALTER TABLE people ADD comment VARCHAR(50) DEFAULT 'TRUE'");
if((!res) || PQresultStatus(res) != PGRES_COMMAND_OK)
{
fprintf(stderr, "Adding col to table (ALTER) Failed: %s", PQerrorMessage(conn));
PQclear(res);
exit_nicely(conn);
}
res = PQexec(conn, "SELECT * FROM people");
if((!res) || (PQresultStatus(res) != PGRES_TUPLES_OK))
{
fprintf(stderr, "SELECT command did not return tuples properly\n");
PQclear(res);
}
int query1 = 2;
res = PQexec(conn,"UPDATE people SET comment='FALSE' WHERE id =\'query1\'");
if((!res) || PQresultStatus(res) != PGRES_COMMAND_OK)
{
fprintf(stderr, "Insertion Failed: %s", PQerrorMessage(conn));
PQclear(res);
exit_nicely(conn);
}
else
printf("Successfully inserted value in Table..... \n");
res = PQexec(conn, "SELECT * FROM people");
if((!res) || (PQresultStatus(res) != PGRES_TUPLES_OK))
{
fprintf(stderr, "SELECT command did not return tuples properly\n");
PQclear(res);
}
puts("==========================");
for(row=0;row<PQntuples(res);row++)
{
for(col=0;col<PQnfields(res);col++)
{
printf("%s\t", PQgetvalue(res, row, col));
}
puts("");
}
PQclear(res);
PQfinish(conn);
return 0;
}
I want the following output:
id | firstname | lastname | comment
1 | Fred | Flintstone | 5055551234 | TRUE
2 | Wilma | Flintstone | 5055551234 | FALSE
5 | XXX | YYY | 7633839276 | TRUE
3 | Barny | Rubble | 5055550000 | TRUE
However, I am getting the following error:
Insertion Failed: ERROR: invalid input syntax for integer: "query1"
LINE 1: UPDATE people SET comment='FALSE' WHERE id ='query1'
Please help me with some suggestions.