Rodolfo Bandeira

Rodolfo Bandeira

software, electronics, security, devops, thoughts

Using postgresql in C programs for Linux

Hi everyone!

In last year at my last Job, I wrote some softwares in linux to access postgresql database. So, I’ll show you how to make a simple code using your favorite text editor and GCC linux compiler. We may use the LIB libpq-dev in our linux.

First step is install libpq-dev using apt-get on Ubuntu of course: 

sudo apt-get install libpq-dev

You may use this code to compile your .C file: 

gcc your_program.c -o your_program -lpq
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // atoi

// Lib used to connect to PostgreSQL database
#include <libpq-fe.h>

#define IP_DB "YOUR_IP"
#define USER_DB "YOUR_USER"
#define PASS_DB "YOUR_PASSWORD"
#define DATABASE_DB "YOUR_DATABASE"

int main () {
  PGconn *conn = NULL;
  PGresult *resultInsert;
  char connection[255];
  char queryString[255];

  sprintf(connection, "host=%s user=%s password=%s dbname=%s", IP_DB, USER_DB, PASS_DB, DATABASE_DB);
  conn = PQconnectdb(stringConexao);

  if(PQstatus(conn) != CONNECTION_OK) {
    printf("\n\n Error while try to connect. \nError: %s  \n\n", PQerrorMessage(conn));
    PQfinish(conn);
  } else {
    printf("\n\n Connected in: %s \n", IP_DB);
  }

  sprintf(
    queryString,
    "INSERT INTO your_table (field_one, field_two, field_three) VALUES (%d, '%s', %d);",
    atoi(valueOne),
    valueTwo,
    valueThree
  );

  resultSelect = PQexec(conn, queryString);

  if(!resultSelect) {
    printf("Error \n");
  } else {
    printf("Ok \n");
  }

  PQfinish(conn);
  printf("\nEND\n");

  return 0;

}

Bye friends, see you!

Rodolfo Bandeira

Last modified:


Share:
LinkedIn
WhatsApp