Previous: , Up: Hello World   [Contents]

5.6 Database operating

GNU Artanis supports mysql/postgresql/sqlite3. We use mysql as an example here.

Please ensure that your DB service was started before you run this code.

If you encounter any problems, it’s very likely it’s with your DB config.

You can use a DB (such as mysql) with GUI tools such as "adminer", independently of the running web-server, e.g. artanis-based.

(use-modules (artanis artanis))
(init-server)
(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")))

This was just a simple introduction. You may read the DB section in this manual for details.

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 loading http://localhost:8080/dbtest in your browser.

Here is quick explanation:

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