Today we needed to access the PostgreSQL database from Objective Caml, the most convenient and advanced framework for working with PostgreSQL was PG'OCAML. In this post, I would like to show a couple of examples of a bunch of Objective Caml and PostgreSQL and how simple it is.
The installation proceeds as follows. If everything happens with you as it is with me in Debian, then PG'OCAML is in the repositories and you just have to do it in the console:
aptitude install libpgocaml-ocaml-devInstallation at this stage is complete, if you have any other distribution, download the package for your distribution, or you can always build from sources.
Let's go directly to a simple example:
let CREATE_TABLE dbh =
PGSQL ( dbh ) "host = MY_HOST" "user = USER"
"password = MY_PASSWORD"
"create temporary table users
(
id serial not null primary key,
name text not null,
age int not null
) "
let insert_user dbh name age =
PGSQL ( dbh ) "INSERT INTO users (name, age)
VALUES ($ name, $ age) "
')
let get_users dbh =
PGSQL ( dbh ) "SELECT * FROM users"
let print_user ( id, name, age ) =
Printf . printf "Id:% ld Name:% s Age:% ld \ n" id name age
let _ =
let dbh = PGOCaml . connect ( ) in
let ( ) = CREATE_TABLE dbh in
let ( ) =
insert_user dbh "John" 30l ;
insert_user dbh "Mary" 40l ;
insert_user dbh "Mark" 42l in
List iter print_user ( get_users dbh )
Here we have the creation of the users table with 3 fields id, name, age in the CREATE_TABLE functional expression, then the 2 insert expressions insert_user and get_users SQL query handlers, add a new user, and accordingly select values from the user table. print_user - output id, name, age values. Then there is a direct connection to our database, PGOCaml.connect (), connection parameters, name, password ... taken from the environment variables of the CREATE_TABLE functional expression. And finally, the work is done directly with the database, adding users insert_user dbh "John" 30l ;, and listing List.iter print_user (get_users dbh) to the list.
ps Official website:
pgocaml