提问人:OrderAndChaos 提问时间:9/5/2023 最后编辑:jthulhuOrderAndChaos 更新时间:9/9/2023 访问量:44
OCAML SQLite3 预准备语句
ocaml sqlite3 prepared statement
问:
我在 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 的新手,有点困惑。任何指导将不胜感激。
答:
2赞
OrderAndChaos
9/5/2023
#1
我已经找到了如何在准备好的语句中绑定参数。
这看起来很冗长,但它仍然是进步。
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"
评论