Previous: , Up: Hello World   [Contents]

4.6 Database operating

GNU Artanis supports mysql/postgresql/sqlite3, we use mysql as a example here.

Please ensure that your DB service was started before you try.

If you encountered any problems, please check your config of DB first. You can use DB without running a server.

(use-module (artanis artanis))
(define conn (connect-db 'mysql #:db-username "your_db_username"
                         #:db-name "your_db_name" #:db-passwd "your_passwd"))
(define mtable (map-table-from-DB conn))
((mtable 'create 'Persons '((name varchar 10) (age integer) (email varchar 20))) 'valid?)
;; ==> #t
(mtable 'set 'Persons #:name "nala" #:age 99 #:email "nala@artanis.com")
(mtable 'get 'Persons #:columns '(name email))
;; ==> ((("name" . "nala") ("email" . "nala@artanis.com")))

Here’s just simple introduction. You may read the DB section in this manual for detail describing.

Of course, you can use DB in your web application.

(get "/dbtest" #:conn #t ; apply for a DB connection from pool
  (lambda (rc)
    (let ((mtable (map-table-from-DB (:conn rc))))
      (object->string
        (mtable 'get 'Persons #:columns '(name email))))))

(run #:use-db? #t #:dbd 'mysql #:db-username "your_db_username"
     #:db-name "your_db_name" #:db-passwd "your_passwd" #:port 8080)

Now, try http://localhost:8080/dbtest in your browser.

Here’re some explains:

Exercise: Return a beautiful table in HTML rather than using object->string.