I'm trying to connect a C script running on Windows to my Postgresql database.
For the moment, I got this script on a website :
#include <stdio.h>
#include "libpq-fe.h"
#include <string>
#include <stdlib.h>
int main() {
PGconn *conn;
PGresult *res;
int rec_count;
int row;
int col;
conn = PQconnectdb("dbname=ljdata host=localhost user=dataman password=supersecret");
if (PQstatus(conn) == CONNECTION_BAD) {
puts("We were unable to connect to the database");
exit(0);
}
res = PQexec(conn,
"update people set phonenumber='5055559999' where id=3");
res = PQexec(conn,
"select lastname,firstname,phonenumber from people order by id");
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
puts("We did not get any data!");
exit(0);
}
rec_count = PQntuples(res);
printf("We received %d records.
", rec_count);
puts("==========================");
for (row=0; row<rec_count; row++) {
for (col=0; col<3; col++) {
printf("%s ", PQgetvalue(res, row, col));
}
puts("");
}
puts("==========================");
PQclear(res);
PQfinish(conn);
return 0;
}
I copied the libpq-fe.h, the postgres_ext.c and the pg_config_ext.c to avoid the errors.
and now I have all this errors :
- undefined reference to 'PQconnectdb'
- undefined reference to 'PQresultStatus'
- ...
So obviously I don't have the file.c which contains all the functions I need but I can't find it.
I saw on another forum I need to create a makefile to tell the compiler to use the libpq.dll (I have this file) but I haven't the knowledge to do that.
How can I make this working ?
EDIT
So now when I try to compile it like that :
gcc -I "C:Program FilesPostgreSQL9.6include" -L "C:Program FilesPostgreSQL9.6lib" test.c -lpq
And I get the error :
C:Program FilesPostgreSQL9.6lib/libpq.dll: file not recognized: File format not recognized
collect2.exe: error: ld returned 1 exit status
I think it's near to the final solution.
From the research I made, I found that libpq.dll is 32bit, but my environnement is 64bit. do this change anything ?
EDIT 2
The compilation now works correctly with this line :
gcc -m64 -I "C:Program FilesPostgreSQL9.6include" -L "C:Program FilesPostgreSQL9.6lib" test.c -lpq -o test.exe
But when I double-click on the .exe I have the following error :
"Unable to start the program because LIBPQ.dll is missing"
So it clearly means that I have to link the libpq.dll with probably a link to Program Files/PG/9.6/lib.
The problem here is that I want to build a standalone .exe which probably embed the Postgresql lib to works correctly even if the computer target haven't Postgresql installed on it
(This is possible, for example in Java when we build a Jar with all the external lib copied in)
Is it possible in C ? I think I need to adapt my compilation line but I don't found which parameter I can add to import all the needed lib in the .exe
See Question&Answers more detail:
os