ocaml sqlite3 准备好的语句

问题描述 投票:0回答:1

我在 ocaml 中有以下 sqlite3 的插入,工作正常。

type article = { author : string; content: string }

let insert_article db (article: article) =
  let sql = Printf.sprintf "INSERT INTO blog (author, content) VALUES ('%s', '%s')" article.author article.content in
  match exec db sql with
  | Rc.OK -> ()
  | _ -> raise @@ Error "Failed to insert"

如何将其转换为使用准备好的语句?

我已经尝试过这种事情,但是没有作者和内容参数的插槽,

let insert_article db (article: article) =
  let sql = prepare db "INSERT INTO blog (author, content) VALUES (?, ?)" article.author article.content in
  match exec db sql with
  | Rc.OK -> ()
  | _ -> raise @@ Error "Failed to insert"

我无法理解这里的 API 类型文档: http://mmottl.github.io/sqlite3-ocaml/api/sqlite3/Sqlite3/index.html#prepared-statements

我是 OCaml 新手,有点困惑。任何指导将不胜感激。

sqlite ocaml prepared-statement
1个回答
0
投票

我已经找到了如何在准备好的语句中绑定参数。

看起来相当冗长,但仍然是进步。

let insert_article db (article : article) =
  let stmt = prepare db "INSERT INTO blog (author, content) VALUES (?, ?)" in
  let authorBind = bind stmt 1 @@ Data.TEXT article.author in
  let contentBind = bind stmt 2 @@ Data.TEXT article.content in
  match (authorBind, contentBind) with
  | Rc.OK, Rc.OK -> (
      match step stmt with 
      | Rc.DONE -> () 
      | _ -> failwith "Failed to insert"
    )
  | _ -> failwith "Failed to bind parameters to the SQL query"
© www.soinside.com 2019 - 2024. All rights reserved.