2

OCaml如何连接PostgreSQL

 2 years ago
source link: https://www.ttalk.im/2019/10/connect-postgresql-with-ocaml.html
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

2019-10-16 :: 编程, OCaml, 便贴

By: David Gao

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

安装Ocaml的PostgreSQL的绑定

opam install postgresql

在PostgreSQL中建立用户和测试表

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,输入下面的代码

#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