Skip to content

Instantly share code, notes, and snippets.

@brandonrachal
Last active August 29, 2015 14:00
Show Gist options
  • Save brandonrachal/11122930 to your computer and use it in GitHub Desktop.
Save brandonrachal/11122930 to your computer and use it in GitHub Desktop.
Connecting to Postgres in C++
#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
#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