Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect to PostgreSQL in Erlang using epgsql driver?

I would like to access a PostgreSQL database in Erlang. I downloaded the epgsql driver, it was a few directories and files, but I don't understand how to use it.

How can I write an Erlang program and use the epgsql driver to access a PostgreSQL database?

I made a new folder and copied all files from src/ in the driver and pgsql.hrl to my new folder. Then I created a simple test program:

-module(dbtest).
-export([dbquery/0]).

dbquery() ->
    {ok,C} = pgsql:connect("localhost", "postgres", "mypassword",
                                     [{database, "mydatabase"}]),
    {ok, Cols, Rows} = pgsql:equery(C, "select * from mytable").

Then I started erl and compiled the modules with c(pgsql). and c(dbtest). But then when I exeute dbtest:dbquery(). I get this error:

** exception error: undefined function pgsql:connect/4
     in function  dbtest:dbquery/0

Any suggestions on how I can connect to a PostgreSQL database using Erlang?

like image 632
Jonas Avatar asked May 29 '11 11:05

Jonas


1 Answers

Rebar is a good tool to use but, I'm finding it's good to know how your project should be structured so you can tell what to do when things go wrong. Try organizing your project like this:

/deps/epqsql/
/src/dbtest.erl
/ebin

Then cd into deps/epqsql and run make to build the library.

Your dbtest.erl file should also explicitly reference the library, add this near the top:

-include_lib("deps/epgsql/include/pgsql.hrl").

You'll probably want to use a Makefile (or rebar) that compiles your code when you make changes but, try this to compile things right now: erlc -I deps/epqsql/ebin -o ebin src/dbtest.erl.

When testing, make sure your load paths are set correctly, try: erl -pz deps/epqsql/ebin/ ebin/. When the erl console loads up, try dbtest:dbquery(). and see what happens!

I don't have Postgresql setup on my machine but, I was able to get more reasonable looking errors with this setup.

like image 84
jdeseno Avatar answered Nov 07 '22 11:11

jdeseno