如何使用cl-pg包?

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

我已经在我的计算机(Raspberry PI 4B)上安装了 clisp 和 cl-pg,以便通过 Lisp 脚本使用 PostGres。

# apt install clisp
# apt install cl-pg

我从here给出的示例代码开始尝试的一些技巧没有任何结果。

   (with-pg-connection (conn "testdb" "login" :host "dbhost" :password "secret")
      (with-pg-transaction conn
         (when (member "test_date" (pg-tables conn) :test #'string=)
            (pg-exec "DROP TABLE test_date"))
         (pg-exec conn "CREATE TABLE test_date(a timestamp, b abstime, c time, d date)")
         (pg-exec conn "INSERT INTO test_date VALUES "
                       "(current_timestamp, 'now', 'now', 'now')")))

是否有一些示例代码可以展示如何使用 cl-pg,包括任何必要的(加载...)或使用此包所需的任何内容?

raspberry-pi common-lisp raspberry-pi4 clisp
1个回答
0
投票

难怪它不起作用,因为你放错了包。 https://pg.common-lisp.dev/ 是 pg-dot-list。不是 cl-pg。

你必须使用这些命令:

(ql:quickload "cl-pg")
(defvar *db-conn* (cl-pg:connect :database "dbname" 
                                 :user "username" 
                                 :password "password" 
                                 :host "localhost" 
                                 :port 5432))

;; execute a command
(defvar *result* (cl-pg:exec *db-conn* "SELECT * FROM your_table;"))

;; iterate over results:
(dolist (row *result*)
  (format t "~A~%" row))

;; finally disconnect your connection:
(cl-pg:disconnect *db-conn*)

这个包中没有给出上下文管理器。 但你可以轻松地在 Common Lisp 中定义一个:

(defmacro with-connection ((conn-var &rest connection-args) &body body)
  `(let ((,conn-var (cl-pg:connect ,@connection-args)))
     (unwind-protect
          (progn ,@body)
       (cl-pg:disconnect ,conn-var))))

;; use it like this:
(with-connection (*db-conn* :database "dbname" 
                                :user "username" 
                                :password "password" 
                                :host "localhost" 
                                :port 5432)
  (let ((result (cl-pg:exec *db-conn* "SELECT * FROM your_table;")))
    (dolist (row result)
      (format t "~A~%" row))))
© www.soinside.com 2019 - 2024. All rights reserved.