Once the database has been created, we are now ready for the coding part. Let’s create a Win32 console application now (I am using visual studio 2005 for this example).
The first task we need to do right now is to include the PostgreSQL C++ interface header file and lib to our project. You can do that by right click your project solution and click properties.
Note 1: You might need to change the following file path accordingly.
[C/C++ -> General -> Additional Include Directories]
C:\Program Files\PostgreSQL\8.4\include
[Linker -> General -> Additional Library Directories]
C:\Program Files\PostgreSQL\8.4\lib
[Linker -> Input -> Additional Dependencies]
libpq.lib
Note 2:At the end of this example, you will need to copy your project output (EXE) to ..\PostgreSQL\8.4\bin. Alternately, you can copy all DLLs located at ..\PostgreSQL\8.4\bin\ to you project output folder.
We will start the coding part in our cpp file now. Make sure that you include the following header accordingly. libpq-fe.h must be included.
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; } |
At this point, if you are running the SELECT statment from the PostgreSQL command console, you will see the same data being display on your C++ win32 console windows.
sample source code: c++ postgresql example
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.