OCaml如何连接PostgreSQL

:: 编程, OCaml, 便贴

By: David Gao

简单记录下如何在OCaml中如何连接PostgreSQL

安装Ocaml的PostgreSQL的绑定

1
opam install postgresql

在PostgreSQL中建立用户和测试表

1
2
3
4
5
6
7
8
CREATE ROLE web;
ALTER ROLE web LOGIN ;
ALTER USER web WITH PASSWORD '123456';

CREATE TABLE compay( 
    id INTEGER PRIMARY KEY,
    name text NOT NULL,
    age integer);

让我们打开OCaml的repl,输入下面的代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#use "topfind";;
#thread;;
#require "postgresql";;

open Printf;;
open Postgresql;;

let conn = new connection ~dbname:"postgres" ~host:"localhost" ~user:"web" ~password:"123456" ();;

let query = "SELECT id, name,age FROM company WHERE id = $1";;

let show res =
  for tuple = 0 to res#ntuples - 1 do
    for field = 0 to res#nfields - 1 do
      printf "%s, " (res#getvalue tuple field)
    done;
    print_newline ()
  done;;

let run s = show @@ conn#exec ~expect:[Tuples_ok] ~params:[| s |] query;;


assert ((conn#prepare "query_company" query)#status = Command_ok);;

let prepared_run s name =
  show @@ conn#exec_prepared ~expect:[Tuples_ok] ~params:[|s|] name
;;

run "1";;
prepared_run "2" "query_company";;