我最近尝试使用OCaml来处理Postgres数据库。我找到了PG'Ocaml库并且坚持了第一个例子。那就是错误:
$ make
ocamlfind ocamlc -package pgocaml,pgocaml.syntax -syntax camlp4o -c test.ml
File "test.ml", line 7, characters 23-146 (end at line 12, character 2):
Camlp4: Uncaught exception: Unix.Unix_error (20 | CstTag21, "connect", "")
File "test.ml", line 1:
Error: Preprocessor error
make: *** [test.cmo] Error 2
这是某种类似的问题(https://lists.gnu.org/archive/html/modcaml/2008-05/msg00000.html),但结论对我不起作用,因为使用
进行记录$ psql -h localhost -d adam - U adam
完全有效,我已经包含了行
let dbh = PGOCaml.connect ~host:"localhost" ~user:"adam" ~datebase:"adam"
~password:"******" () in
进入我的代码。
这是我的Makefile:
PROJECT := test
LINK_PKG := pgocaml
COMP_PKG := pgocaml,pgocaml.syntax
all: $(PROJECT)
$(PROJECT): $(PROJECT).cmo
ocamlfind ocamlc -package $(LINK_PKG) -linkpkg -o $@ $<
$(PROJECT).cmo: $(PROJECT).ml
ocamlfind ocamlc -package $(COMP_PKG) -syntax camlp4o -c $<
这就是整个代码:
open Printf
let () =
let dbh = PGOCaml.connect ~host:"localhost" ~user:"adam" ~datebase:"adam"
~password:"******" () in
PGSQL(dbh) "execute" "create temporary table employees (
id serial not null primary key,
name text not null,
salary int4 not null,
email text
)";
let insert =
PGPREPARE(dbh) "opt-args"
"insert into employees (name, salary, email)
values ($name, $salary, $?email)"
in
insert "Ann" 10_000_l ();
insert "Bob" 45_000_l ();
insert "Jim" 20_000_l ();
insert ~name:"Mary" ~salary:30_000_l ~email:"mary@example.com" ();
let rows = PGSQL(dbh) "select id, name, salary, email from employees" in
List.iter (
fun (id, name, salary, email) ->
let email = match email with Some email -> email | None -> "-" in
printf "%ld %S %ld %S\n" id name salary email
) rows;
let ids = [ 1_l; 3_l ] in
let rows = PGSQL(dbh) "select id, name, salary, email from employees
where id in $@ids" in
List.iter (
fun (id, name, salary, email) ->
let email = match email with Some email -> email | None -> "-" in
printf "%ld %S %ld %S\n" id name salary email
) rows;
PGOCaml.close dbh