Home > Programming > How To – Creating a Variable Query in PostGreSQL using libpq in C

How To – Creating a Variable Query in PostGreSQL using libpq in C

December 18th, 2014

If you don’t have libpq, you can install it using the following command in Debian

apt-get install libpq-dev

The following code shows how to create an INSERT query using strings and pass it on to the PQexec() function.

#include

#include

//#include

//

#include

int     main() {

PGconn          *conn;

PGresult        *res;

int             rec_count;

int             row;

int             id = 1;

char           dtype = ‘W’;

char           maci[19] = {0};

char            buf[256] = {0};

snprintf(maci,18,”E8:4E:84:A8:68:9C”);

puts(maci);

//      while (id < 20)

//      {

conn = PQconnectdb(“dbname=test host=192.168.1.1 user=root password=test”);

if (PQstatus(conn) == CONNECTION_BAD)

{

puts(“We were unable to connect to the database”);

exit(0);

}

sprintf(buf, “INSERT INTO counter(mac, device_id, device_type)  VALUES(‘%s’,%d,’%c’)”,maci,id,dtype);

puts(buf);

res = PQexec(conn, buf);

if (PQresultStatus(res) == PGRES_COMMAND_OK)

{

puts(“Alhamdulillah!”);

}

else

{

exit(0);

}

PQclear(res);

PQfinish(conn);

//      id = id + 1;

//}

return 0;

}

 

Be Sociable, Share!
Categories: Programming Tags:

Comments Closed

Comments are closed.