Previous: , Up: Hello World   [Contents]

5.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 encounter any problems, please check your config of DB first.

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

(use-modules (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)))
;; ==> #t
(mtable 'set 'Persons #:name "nala" #:age 99 #:email "")
(mtable 'get 'Persons #:columns '(name email))
;; ==> ((("name" . "nala") ("email" . "")))

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))))
          (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 are some explanations:

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