Last active
August 29, 2015 14:00
-
-
Save brandonrachal/11122930 to your computer and use it in GitHub Desktop.
Connecting to Postgres in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Install on Ubuntu: | |
#sudo apt-get install libpqxx-3.1 | |
#sudo apt-get install libpqxx3-dev | |
all: RunPostgresConnect | |
RunPostgresConnect: PostgresConnect.o | |
g++ -o $@ $< -lpqxx -lpq | |
PostgresConnect.o: PostgresConnect.cpp | |
g++ -c $< | |
clean: | |
rm PostgresConnect.o RunPostgresConnect |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <pqxx/pqxx> | |
using namespace std; | |
using namespace pqxx; | |
int main() { | |
try { | |
connection conn("host=localhost dbname=SomeDatabase user=SomeUser password=SecretPassword"); | |
work transaction(conn, "TestTransaction"); | |
result results = transaction.exec( "select * from posts where id=4"); | |
transaction.commit(); | |
cout << "Results count: " << results.size() << endl; | |
for (result::const_iterator row = results.begin(); row != results.end(); ++row) { | |
for (result::tuple::const_iterator field = row->begin(); field != row->end(); ++field) { | |
cout << field->c_str() << '\t'; | |
} | |
cout << endl; | |
} | |
conn.disconnect(); | |
} catch(const exception &ex) { | |
cerr << ex.what() << endl; | |
return 1; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment