6

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?

Jonas
  • 121,568
  • 97
  • 310
  • 388
  • 1
    Not a direct answer for you question, but - read about rebar. It's describes how to organize your application and their dependecies. – Sergey Miryanov May 29 '11 at 14:32

2 Answers2

6

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.

jdeseno
  • 7,753
  • 1
  • 36
  • 34
  • I am getting make: rebar: Command not found make: *** [compile] Error 127. Check http://stackoverflow.com/questions/33485205/how-to-build-and-use-epgsql-erlang – Kamrul Khan Nov 02 '15 at 22:45
-4

I recommend to use ejabber pgsql driver https://svn.process-one.net/ejabberd-modules/pgsql/trunk/

user636845
  • 13
  • 3