

1 2 | #include <string> #include "libpq-fe.h" |
1 2 3 4 5 6 7 | /* Close connection to database */ void CloseConn(PGconn *conn) { PQfinish(conn); getchar(); exit(1); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | /* Establish connection to database */ PGconn *ConnectDB() { PGconn *conn = NULL; // Make a connection to the database conn = PQconnectdb("user=postgres password=test123 dbname=testdb hostaddr=127.0.0.1 port=5432"); // Check to see that the backend connection was successfully made if (PQstatus(conn) != CONNECTION_OK) { printf("Connection to database failed"); CloseConn(conn); } printf("Connection to database - OK\n"); return conn; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | /* Create employee table */ void CreateEmployeeTable(PGconn *conn) { // Execute with sql statement PGresult *res = PQexec(conn, "CREATE TABLE employee (Fname char(30), Lname char(30))"); if (PQresultStatus(res) != PGRES_COMMAND_OK) { printf("Create employee table failed"); PQclear(res); CloseConn(conn); } printf("Create employee table - OK\n"); // Clear result PQclear(res); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | /* Append SQL statement and insert record into employee table */ void InsertEmployeeRec(PGconn *conn, char * fname, char * lname) { // Append the SQL statment std::string sSQL; sSQL.append("INSERT INTO employee VALUES ('"); sSQL.append(fname); sSQL.append("', '"); sSQL.append(lname); sSQL.append("')"); // Execute with sql statement PGresult *res = PQexec(conn, sSQL.c_str()); if (PQresultStatus(res) != PGRES_COMMAND_OK) { printf("Insert employee record failed"); PQclear(res); CloseConn(conn); } printf("Insert employee record - OK\n"); // Clear result PQclear(res); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | /* Fetch employee record and display it on screen */ void FetchEmployeeRec(PGconn *conn) { // Will hold the number of field in employee table int nFields; // Start a transaction block PGresult *res = PQexec(conn, "BEGIN"); if (PQresultStatus(res) != PGRES_COMMAND_OK) { printf("BEGIN command failed"); PQclear(res); CloseConn(conn); } // Clear result PQclear(res); // Fetch rows from employee table res = PQexec(conn, "DECLARE emprec CURSOR FOR select * from employee"); if (PQresultStatus(res) != PGRES_COMMAND_OK) { printf("DECLARE CURSOR failed"); PQclear(res); CloseConn(conn); } // Clear result PQclear(res); res = PQexec(conn, "FETCH ALL in emprec"); if (PQresultStatus(res) != PGRES_TUPLES_OK) { printf("FETCH ALL failed"); PQclear(res); CloseConn(conn); } // Get the field name nFields = PQnfields(res); // Prepare the header with employee table field name printf("\nFetch employee record:"); printf("\n********************************************************************\n"); for (int i = 0; i < nFields; i++) printf("%-30s", PQfname(res, i)); printf("\n********************************************************************\n"); // Next, print out the employee record for each row for (int i = 0; i < PQntuples(res); i++) { for (int j = 0; j < nFields; j++) printf("%-30s", PQgetvalue(res, i, j)); printf("\n"); } PQclear(res); // Close the emprec res = PQexec(conn, "CLOSE emprec"); PQclear(res); // End the transaction res = PQexec(conn, "END"); // Clear result PQclear(res); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | /* Erase all record in employee table */ void RemoveAllEmployeeRec(PGconn *conn) { // Execute with sql statement PGresult *res = PQexec(conn, "DELETE FROM employee"); if (PQresultStatus(res) != PGRES_COMMAND_OK) { printf("Delete employees record failed."); PQclear(res); CloseConn(conn); } printf("\nDelete employees record - OK\n"); // Clear result PQclear(res); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | /* Drop employee table from the database*/ void DropEmployeeTable(PGconn *conn) { // Execute with sql statement PGresult *res = PQexec(conn, "DROP TABLE employee"); if (PQresultStatus(res) != PGRES_COMMAND_OK) { printf("Drop employee table failed."); PQclear(res); CloseConn(conn); } printf("Drop employee table - OK\n"); // Clear result PQclear(res); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | int _tmain(int argc, _TCHAR* argv[]) { PGconn *conn = NULL; conn = ConnectDB(); CreateEmployeeTable(conn); InsertEmployeeRec(conn, "Mario", "Hewardt"); InsertEmployeeRec(conn, "Daniel", "Pravat"); FetchEmployeeRec(conn); printf("\nPress ENTER to remove all records & table.....\n"); getchar(); RemoveAllEmployeeRec(conn); DropEmployeeTable(conn); CloseConn(conn); return 0; } |


Thanks for your help!!
It works very well! 🙂
Matt
I’m getting these errors, the tutorial don’t explained well how to organize those files for newbies like me.
Error 1 error LNK2019: unresolved external symbol _PQfinish referenced in function “void __cdecl CloseConn(struct pg_conn *)” (?CloseConn@@YAXPAUpg_conn@@@Z) c:\Users\Dezt\documents\visual studio 2010\Projects\PSQLTest\PSQLTest\PSQLTest.obj PSQLTest
Error 2 error LNK2019: unresolved external symbol _PQstatus referenced in function “struct pg_conn * __cdecl ConnectDB(void)” (?ConnectDB@@YAPAUpg_conn@@XZ) c:\Users\Dezt\documents\visual studio 2010\Projects\PSQLTest\PSQLTest\PSQLTest.obj PSQLTest
Error 3 error LNK2019: unresolved external symbol _PQconnectdb referenced in function “struct pg_conn * __cdecl ConnectDB(void)” (?ConnectDB@@YAPAUpg_conn@@XZ) c:\Users\Dezt\documents\visual studio 2010\Projects\PSQLTest\PSQLTest\PSQLTest.obj PSQLTest
Error 5 error LNK2019: unresolved external symbol _PQresultStatus referenced in function “void __cdecl CreateEmployeeTable(struct pg_conn *)” (?CreateEmployeeTable@@YAXPAUpg_conn@@@Z) c:\Users\Dezt\documents\visual studio 2010\Projects\PSQLTest\PSQLTest\PSQLTest.obj PSQLTest
Etc.
the error seem like you are missing the reference to the library. Try to check if your project properties [c/c++ or linker]
thanks for example .
it is so good.
Thanks for you clear explanation!
Its work great!
Excellent tutorial. Shame that the source code boxes are so squished. It helped me out massively regardless.
Thank!
nice !
Thanks!
Thank you so much, i’ve been trying for a long time to get a database library actually working. This tutorial was so simple and it actually works! which is more than i can say for most tutorials i’ve found
I am a beginer of c++ and PostgreSQL, This tutorial help me so much, It passed build with no error and work well for the first time. Thank you!Could you give me more materials about integrating the PostgreSQL into the C++ project?
My email: mengfanbin2011@gmail.com
Nice tutorial, but I also get the same errors as Reinaldo C. Filho.
I have done what “Note 1” says:
Note 1: You might need to change the following file path accordingly.
[C/C++ -> General -> Additional Include Directories]
[Linker -> General -> Additional Library Directories]
[Linker -> Input -> Additional Dependencies]
libpq.lib
Any ideas?
i am getting the same error regarding unresolved external symbol as follow
>login.obj : error LNK2019: unresolved external symbol _PQfinish referenced in function “void __cdecl CloseConn(struct pg_conn *)” (?CloseConn@@YAXPAUpg_conn@@@Z)
1>login.obj : error LNK2019: unresolved external symbol _PQstatus referenced in function “struct pg_conn * __cdecl ConnectDB(void)” (?ConnectDB@@YAPAUpg_conn@@XZ)
1>login.obj : error LNK2019: unresolved external symbol _PQconnectdb referenced in function “struct pg_conn * __cdecl ConnectDB(void)” (?ConnectDB@@YAPAUpg_conn@@XZ)
1>D:\Hemant\win32 programs\win32 tasks\Task1 login Module\Debug\Task1 login Module.exe : fatal error LNK1120: 3 unresolved externals
i am beginer in this so can anyone give step by step instruction to solve this error ?????
i am getting the same error regarding unresolved external symbol as follow
>login.obj : error LNK2019: unresolved external symbol _PQfinish referenced in function “void __cdecl CloseConn(struct pg_conn *)” (?CloseConn@@YAXPAUpg_conn@@@Z)
1>login.obj : error LNK2019: unresolved external symbol _PQstatus referenced in function “struct pg_conn * __cdecl ConnectDB(void)” (?ConnectDB@@YAPAUpg_conn@@XZ)
1>login.obj : error LNK2019: unresolved external symbol _PQconnectdb referenced in function “struct pg_conn * __cdecl ConnectDB(void)” (?ConnectDB@@YAPAUpg_conn@@XZ)
1>D:\Hemant\win32 programs\win32 tasks\Task1 login Module\Debug\Task1 login Module.exe : fatal error LNK1120: 3 unresolved externals
i am beginner in this so can anyone give step by step instruction to solve this error ?????
Problem from my last message (on April 15th, 2011 10:18 pm) is solved (partially).
Last I tried to work on VS2010 and x64 PostgreSQL Installer version 9.0.4-1. I got errors listed in prev. message.
The solution I found is to use VS2005 and PostgreSQL Installer version 8.4.8-1. It all works fine now.
Any ideas how to get it working on VS2010?
Thanks for the tutorial.
Thank’s for your tutorial.
it’s work on me, and now i can get to the next level.
I am planning on loading a high volume of records off a data stream into an existing table. The tutorial is for a simple case of loading one record at a time but if you had 1 million records to load quickly what would be the best way using C++ and postgreSQL?
i install postgresql 8.0.1 in redhat.and i write the tutorial but failed.
g++ -o test -I /usr/local/pgsql/include -L /usr/local/pgsql/LIB test.cpp
Excellent !
I needed most basic yet whole example of PostgreSQL implementation through Visual C++ as example to point to … This was more than enough .
Thank You Very Much for Your effort .
Thanks a ton for the insightful tutorial ! I have been searching for such a tutorial for months !!
Great job dude.
Thank you…i spent 3 days looking for this 😀
I am getting an error related to the _TCHAR not being able to be resolved.
Could you tell me what equivalent that I need to add/change for eclipse on my MAC?
Thanks,
RIck
Chang to wstring in case you need to support unicode, otherwise use char
Thank you, just what i was looking for!
I am looking the same but using free GNU, like codeblocks, I can have a run connection to postgre.
Could you help me with that.
My first shot to pqSql ever = successfull!
Thank you very much.
If we have postgres\bin in the path why those 4.5 Mb of dll’s should be in (every) program directory?
Windows7, Pq 9.1, gcc/mingw.
Hello can you guys help newbie here i tried following the said instruction but im getting this error
1>pgsample.obj : error LNK2019: unresolved external symbol _PQfinish referenced in function _main
1>pgsample.obj : error LNK2019: unresolved external symbol _PQstatus referenced in function _main
1>pgsample.obj : error LNK2019: unresolved external symbol _PQsetdbLogin referenced in function _main
1>D:\dvrfiles\src_sample\test\sample\Debug\sample.exe : fatal error LNK1120: 3 unresolved externals
im using MVS 2010, thanks in advanced.
I tried with VS2012 C++ Express together with PostgreSQL 9.1.3 in my 32bit Windows 7 dev machine and it seem that this tutorial is compatible with PostgreSQL 8.x and VS2005 as well.
Please check your C++ project properties and make sure that you have the following setting in place.
[C/C++ -> General -> Additional Include Directories]
C:\Program Files\PostgreSQL\9.1\include
[Linker -> General -> Additional Library Directories]
C:\Program Files\PostgreSQL\9.1\lib
[Linker -> Input -> Additional Dependencies]
libpq.lib
From your errors, you probably missing to include “libpq.lib” in the [Linker -> Input -> Additional Dependencies]
The linking errors you are getting depend on the platform you are using. If you have 32bit postgres, complie the source as Win32. For 64bit postgres use x64 platform.
This can be set in Project -> Properties -> Platform or Configuration Manager…
With VS 2008 and PostgreSQL 9.1 it does NOT WORK !!!!
I checked the settings (see post of askyb) and I got a lot of
error LNK2019: unresolved external symbol
What is wrong: VS 2008 or PostgreSQL 9.1 ????
Has someone compile successfuly with these software ?
It works !
Attentions what version you installed on windows x32 or x64 !
Many thanks to author for this tutorial!
But I had the same problem with postgreses > 9.0. Probable, this errors occurs because of mismatch of header and lib file.
If you use W7 + Visual Studio Cpp 2012 + PostgreSQL, all 32bits, you need configure:
[C/C++ -> General -> Additional Include Directories]
C:\Program Files\PostgreSQL\9.2\include
[Linker -> General -> Additional Library Directories]
C:\Program Files\PostgreSQL\9.2\lib
[Linker -> Input -> Additional Dependencies] libpq.lib
and insert in your folder DEBUG (or where your exe file) the libintl.dll + libpq.dll that are in the bin folder from POSTGRESQL
If you need to connect Windows 7 + PostGreSQL 9.2 + BORLAND BUILDER 6 (2002) all 32bits
you need:
Project->Options->Directories/Conditionals.
1 – Set in Include Path: C:\Program Files\PostgreSQL\9.2\include
2 – Set de Library path:
C:\Program Files\PostgreSQL\9.2\lib
put all this files on top.
3 – Put in your folder project (where the file EXE is generated), the libintl.dll + libpq.dll
4 – open the cmd prompt, and go to the folder PostGreSQL/9.2/bin.
In cmd, type: implib -a libpq.lib libpq.dll.
the libpq.lib is generate.
Go to the ProjectManager, in Builder Cpp, and in your project add, the libpq.lib, generated by setp 4.
Build and Make your project.
Run!
If you use:
PostGreSQL 9.2 32bits and NetBeans 7.3.1 Cpp
+ W7 Professional SP-1 x86
+ MingW-gcc 4.4
+ qt-win-4.8.5
+ msys-1.0.11
+ Java 7u25(for netbeans)
In netbeans go to:
File->Project Properties
In Project Properties, go to “”” C++ Compiler “””
Include Directories add: “C:/Program Files/PostgreSQL/9.2/include”
Select store path as ABSOLUTE.
GO back to Categories, and set LINKER:
Add Library File and add:
C:/Program Files/PostgreSQL/9.2/lib/libpq.lib
Select store path as ABSOLUTE.
Apply !!!
Go to folder:
C:\Users\Yourname\Documents\NetBeansProjects\YourAplication\dist\Debug\MinGW-Windows
and insert in your folder (where your exe file) the libintl.dll + libpq.dll that are in the bin
folder from POSTGRESQL 9.2
Go back to netbeans clean and build project (Shift + F11) !!
Copy the code present in this page, preserve your header includes
Thats all
Hello, you know to inform the error this statement – line 2
1 void armazenacoordenadas(int x, int y){
2 result = PQexec(conn, “insert into coordenadasred values (‘”x”‘,'”y”‘)”);
3 }
For some reason libpq only works in cdecl c++. doesn’t work with stdcall. Have to declare the code calling it cdecl, but it links fine to stdcall code. Very weird.
Yes, Postgres 64’s distribution doesn’t work contain a Win32 LIB. That’s pretty dumb. If you have a Win64 system of course you’ll install the 64-bit version, but that doesn’t mean every application you write will be 64-bit. Far from it. 32-bit is fine most of the time. Postgres distribution should contain both win32 and win64 so you can use either API from either.
These linking problems have been around for many years. About time Postgresql cleaned them up. Why put so many people through unnecessary torment?
Very nice example! However, I need to use this library in Eclipse C++ CDT, and I’m not sure whether it can hold the libpq.lib (I think it uses .a libraries). Can you say how is it done in Eclipse? BTW, I use Windows 7 – 64 bits, and Eclipse Kepler.
The following program compile ok but when build, it gives some errors:
C:UsersDouglasAppDataLocalTempccAebC8L.o:postgres.cpp:(.text+0x6b): undefined reference to
PQconnectdb'
PQstatus’C:UsersDouglasAppDataLocalTempccAebC8L.o:postgres.cpp:(.text+0x79): undefined reference to
……
I am using C++ with Windows 7.
Where are PQconnectdb, PQstatus, `PQfinish’, etc?
I appreciate your help
Best regards,
Douglas
THIS ISTHE PROGRAM:
#include “include/libpq-fe.h”
//#include “bin/libpq.dll”
using namespace std;
int main()
{
PGconn *ConnectDB();
PGconn *conn = NULL;
conn = ConnectDB();
cout << "conn: " << conn;
//CreateEmployeeTable(conn);
//InsertEmployeeRec(conn, "Mario", "Hewardt");
//InsertEmployeeRec(conn, "Daniel", "Pravat");
//FetchEmployeeRec(conn);
//printf("nPress ENTER to remove all records & table…..n");
//getchar();
//RemoveAllEmployeeRec(conn);
//DropEmployeeTable(conn);
//CloseConn(conn);
return 0;
}
/* Establish connection to database */
PGconn *ConnectDB()
{
PGconn *conn = NULL;
// Make a connection to the database
conn = PQconnectdb("user=postgres password=vacorp dbname=platinum hostaddr=127.0.0.1 port=5432");
// Check to see that the backend connection was successfully made
if (PQstatus(conn) != CONNECTION_OK)
{
printf("Connection to database failed");
//CloseConn(conn);
PQfinish(conn);
}
printf("Connection to database – OKn");
return conn;
}
/* Close connection to database */
void CloseConn(PGconn *conn)
{
PQfinish(conn);
getchar();
//exit(1);
}
My friend I really enjoyed your tutorial, I’ll try later at my home with Visual C++.
thanks