Here's how I used this to connect to a PostgreSQL database called 'names' with username 'names' password 'names' and table named 'names'.
First, you need to install the libraries you need. Start by installing the PostgreSQL server. Then, install libpgeasy. Now you're ready to begin.
Create a PostgreSQL server database called 'names', accessible with user 'names' by password 'names'. Then, open it and create a table 'names' and make it accessible by this username 'names'. The columns should be firstname varchar(30), lastname varchar(30). Then, insert some rows in there.
Now create a C script (name it /tmp/tester, for now) like so:
Code:
#!/usr/bin/C
#include <postgresql/libpq-fe.h>
#include <libpgeasy.h>
char firstname [30+1];
char lastname [30+1];
PGconn * connection;
connection = connectdb("dbname=names user=names password=names host=localhost");
on_error_stop();
doquery("SELECT * FROM names");
while ( fetch (firstname, lastname) != END_OF_TUPLES ) {
printf("%s %s\n", firstname, lastname);
}
disconnectdb();
And now there's a special way you'll need to call this. Even though you have #!/usr/bin/C at the top, it won't work to simply call:
/tmp/tester
You'll end up with errors like:
source.c:(.text+0x2a): undefined reference to `connectdb'
source.c:(.text+0x32): undefined reference to `on_error_stop'
source.c:(.text+0x3e): undefined reference to `doquery'
source.c:(.text+0x6c): undefined reference to `fetch'
source.c:(.text+0x76): undefined reference to `disconnectdb'
collect2: ld returned 1 exit status
So, the fix is to run it like this:
C -cL/usr/lib/libpgeasy.so -clpgeasy /tmp/tester
To take this to another level, you could then use preprocessor directives like crazy to make this into your own mini "programming language" (of sorts) with database access.
Note that this script will run sort of slow on the first time, but on all subsequent hits, the script will run blazingly fast because it is compiled as a true C program.
As an added bonus, if you call this with exec() from PHP, you can speed up PHP to do various tasks that it might do slowly or ineffectively.
Bookmarks