2

OCaml 使用 PostgreSQL

 3 years ago
source link: https://www.ttalk.im/pages/995338350741159955
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

OCaml 使用 PostgreSQL

安装Ocaml的PostgreSQL的绑定

opam install postgresql

在PostgreSQL中建立用户


CREATE ROLE web;
ALTER ROLE web LOGIN ;
ALTER USER web WITH PASSWORD '123456';

在PostgreSQL建立一张表


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

让我们打开OCaml的交互编程,输入下面的代码


#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";;

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK