<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/">
    <channel>
        <title>Tutorial :: Clj-DBCP Clojure Library for Connecting to CUBRID Database</title>
        <link>http://www.cubrid.org/?mid=clj_dbcp</link>
        <description>Tutorial :: Clj-DBCP Clojure Library for Connecting to CUBRID Database</description>
        <language>en</language>
        <pubDate>Thu, 30 Dec 2010 11:47:39 -0800</pubDate>
        <lastBuildDate>Fri, 16 Sep 2011 09:01:46 -0800</lastBuildDate>
        <generator>XpressEngine 1.4.4.1</generator>
                        										        <item>
            <title>Tutorial :: Clj-DBCP Clojure Library for Connecting to CUBRID Database</title>
            <dc:creator>admin</dc:creator>
            <link>http://www.cubrid.org/clj_dbcp</link>
            <guid isPermaLink="true">http://www.cubrid.org/clj_dbcp</guid>
                                    <description><![CDATA[<h1>Clj-DBCP Clojure Library for Connecting to CUBRID Database</h1>

<p><b>Clj-DBCP</b> is a Java-6/Clojure library to create a database connection pool, which is known to be a more efficient way to connect to multiple databases in a transaction-heavy environment.</p>

<h4>Why do we need a connection pool?</h4>

<p>Often you encounter with a situation when you have to allow multiple users to connect to a database, extract some data, then insert this data either modified or as it is to another database. Opening and maintaining a database connection for each user, especially when requests made to a dynamic database-driven website application, is costly and wastes resources.</p><p>Here comes a connection pool (<i>and here we can benefit from Clj-DBCP</i>), a cache of database connections maintained so that the connections can be reused when future requests to the database are required. Connection pools are used to enhance the performance of executing commands on a database. In connection pooling, after a connection is created, it is placed in the pool and it is used over again so that a new connection does not have to be established. If all the connections are being used, a new connection is made and is added to the pool. Connection pooling also cuts down on the amount of time a user must wait to establish a connection to the database.</p>

<div class="contents-table">
<h3>Table of Contents</h3>
<ul>
<li><a class="toTop">Back to Top</a></li>
<li><a href="#downloads">Downloads</a></li>
<ul>
<li><a href="#source-code">Source Code</a></li>
<li><a href="#sample">Sample Project</a></li>
</ul>
<li><a href="#example">Example</a></li>
<ul>
<li><a href="#sample-output">Sample Leiningen test output</a></li>
</ul>
<li><a href="#see-also">See also</a></li>
<li><a href="#getting-help">Getting Help</a></li>
</ul>
</div>

<h2 id="downloads">Downloads</h2>

<p>Clj-DBCP JARs can be downloaded as a Maven/Leiningen/Cake dependency from Clojars: <a href="http://clojars.org/org.bituf/clj-dbcp" target="_blank">http://clojars.org/org.bituf/clj-dbcp</a>.</p>

<h3 id="source-code">Source Code</h3>

<p>The source code for Clj-DBCP can be forked/downloaded at <a href="https://bitbucket.org/kumarshantanu/clj-dbcp/src" target="_blank">https://bitbucket.org/kumarshantanu/clj-dbcp/src</a>. The source code page also includes a short tutorial on how to use Clj-DBCP - scroll down on the page to find it.</p>

<h3 id="sample">Sample Project</h3>

<p>Download a <a href="/files/docs/tutorials/clj-dbcp/cubrid-crud.zip">sample Clj-DBCP project</a> which connects to the CUBRID Database and performs basic CRUD (Create, Retrieve, Update, Delete) operations.</p>

<h2 id="example">Example</h2>

<ul>
<li>Create a project using Leiningen where <b>cubrid-crud</b> is the name of the project. Then enter the project directory. If you do not have Leiningen, download and install it from <a href="https://github.com/technomancy/leiningen" target="_blank">https://github.com/technomancy/leiningen</a>.</li>
<div class="code">
<div editor_component="code_highlighter" code_type="bash" file_path="" description="" first_line="1" collapse="false" nogutter="false" nocontrols="false">
lein new cubrid-crud
cd cubrid-crud
</div>
</div>
<li>Edit the newly generated <b>project.clj</b> file:</li>
<div class="code">
<div editor_component="code_highlighter" code_type="bash" file_path="" description="" first_line="1" collapse="false" nogutter="false" nocontrols="false">
(defproject cubrid-crud "1.0.0"
  :description "CRUD example using CUBRID database"
  :dependencies [[org.clojure/clojure "1.2.0"]
                 [org.clojure/clojure-contrib "1.2.0"]
                 [org.bituf/clj-dbcp "0.3"]
                 [org.clojars.cubrid/cubrid-jdbc "8.3.1.0173"]])
</div>
</div>
<li>Get the dependencies. This will install all the prerequisites.</li>
<div class="code">
<div editor_component="code_highlighter" code_type="bash" file_path="" description="" first_line="1" collapse="false" nogutter="false" nocontrols="false">
lein deps
</div>
</div>
<li>Navigate to the <b>/src</b> directory and edit the <b>dbconfig.properties</b> file. We will use the <b>demodb</b> database which is created by default in CUBRID. The username for it is <b>dba</b> which does not require any password. Change the values according to your database settings if needed.</li>
<div class="code">
<div editor_component="code_highlighter" code_type="bash" file_path="" description="" first_line="1" collapse="false" nogutter="false" nocontrols="false">
hostport=localhost:33000
database=demodb
username=dba
password=
</div>
</div>
<li>Navigate to the <b>/src/cubrid-crud</b> directory and edit the <b>core.clj</b> file:</li>
<div class="code">
<div editor_component="code_highlighter" code_type="bash" file_path="" description="" first_line="1" collapse="false" nogutter="false" nocontrols="false">
;; require the necessary dependencies
(ns cubrid-crud.core
  (:require
    [clojure.contrib.java-utils :as ju]
    [clojure.contrib.sql        :as sql]
    [org.bituf.clj-dbcp         :as dbcp]))

;; load the database configurations
(def config (ju/read-properties "src/dbconfig.properties"))

;; create a function which will perform all operations one by one.
(defn test-crud
    [dbspec]
    (let [table :emp
          orig-record {:id 1 :name "Bashir" :age 40}
          updt-record {:id 1 :name "Shabir" :age 50}
          drop-table  #(sql/do-commands "DROP TABLE emp")
          retrieve-fn #(sql/with-query-results
                         rows
                         ["SELECT * FROM emp WHERE id=?" 1]
                         (first rows))]
      (sql/with-connection
        dbspec
        
        ;; drop table if exists
        (try
          (println "Dropping table")
          (drop-table)
          (catch Exception _
            (println "Cannot drop table; probably doesn't exist?")))
        
        ;; create table
        (println "Creating table")
        (sql/do-commands
          "CREATE TABLE emp (id INTEGER, name VARCHAR(50), age INTEGER)")
        
        ;; insert
        (println "Inserting a row" orig-record)
        (sql/insert-values
          table (keys orig-record) (vals orig-record))
        
        ;; retrieve-check
        (println "Retrieving row")
        (let [row (retrieve-fn)]
          (println row))
        
        ;; update
        (println "Updating row" updt-record)
        (sql/update-values
          table ["id=?" 1] updt-record)
        
        ;; retrieve-check
        (println "Retrieving row")
        (let [row (retrieve-fn)]
          (println row))
        
        ;; delete - TODO
        (println "Deleting row")
        (sql/do-commands
          "DELETE FROM emp WHERE id=1")
        
        ;; drop table
        (println "Dropping table")
        (drop-table))))

;; main function which will be called from Leiningen test
(defn perform-crud
  "Use connection properties to create a connection-pooled DataSource"
  []
  (let [hostport (get config "hostport")
        database (get config "database")
        username (get config "username")
        password (get config "password")
        dbspec (dbcp/db-spec
                 (dbcp/cubrid-datasource
                   hostport database username password))]
    (test-crud dbspec)))
</div>
</div>
<li>Navigate to the <b>/test/cubrid-crud/test</b> directory and edit the <b>core.clj</b> file:</li>
<div class="code">
<div editor_component="code_highlighter" code_type="bash" file_path="" description="" first_line="1" collapse="false" nogutter="false" nocontrols="false">
(ns cubrid-crud.test.core
  (:use [cubrid-crud.core] :reload)
  (:use [clojure.test]))

(deftest replace-me ;; write
         (perform-crud))
</div>
</div>
<li>Start the CUBRID Service and the <i>demodb</i> database.</li>
<div class="code">
<div editor_component="code_highlighter" code_type="bash" file_path="" description="" first_line="1" collapse="false" nogutter="false" nocontrols="false">
cubrid service start
cubrid server start demodb
</div>
</div>
<li>Run this example as Leiningen test.</li>
<div class="code">
<div editor_component="code_highlighter" code_type="bash" file_path="" description="" first_line="1" collapse="false" nogutter="false" nocontrols="false">
lein test
</div>
</div>
</ul>

<p class="important">If your project displays tons of errors, make sure you have started the CUBRID Service and the demodb database.</p>

<h3 id="sample-output">Sample Leiningen test output</h3>

<p>The code above first will display an error message that the table we try to drop does not exist. Then it will create that table, insert the new record, select that record, update it, select again, delete that row, and finally drop the table.</p>

<div class="code">
<div editor_component="code_highlighter" code_type="bash" file_path="" description="" first_line="1" collapse="false" nogutter="false" nocontrols="false">
Testing cubrid-crud.test.core
Dropping table
CUBRIDException:
 Message: Semantic: Class emp does not exist. drop emp
 SQLState: null
 Error Code: -494
Cannot drop table; probably doesn't exist?
Creating table
Inserting a row {:id 1, :name Bashir, :age 40}
Retrieving row
{:id 1, :name Bashir, :age 40}
Updating row {:id 1, :name Shabir, :age 50}
Retrieving row
{:id 1, :name Shabir, :age 50}
Deleting row
Dropping table
Ran 1 tests containing 0 assertions.
0 failures, 0 errors.
</div>
</div>

<h2 id="see-also">See also</h2>

<ul>
<li><a href="https://bitbucket.org/kumarshantanu/clj-dbcp/src" target="_blank">Clj-DBCP Tutorial</a></li>
<li><a href="http://bitumenframework.blogspot.com/2010/10/crud-in-clojure.html" target="_blank">CRUD in Clojure</a> - Bitumen Framework blog</li>
<li><a href="/tutorials">CUBRID Tutorials</a></li>
</ul>

<h2 id="getting-help">Getting Help</h2>

<p>To report bugs, visit <a href="https://bitbucket.org/kumarshantanu/clj-dbcp/issues" target="_blank">https://bitbucket.org/kumarshantanu/clj-dbcp/issues</a>.</p>

<p>If you have any concerns/ideas/comments, post them in the Google Groups at <a href="http://groups.google.com/group/bitumenframework" target="_blank">http://groups.google.com/group/bitumenframework</a>.</p>

<p>Alternatively, post your message to the CUBRID Apps &amp; Tools Forum at <a href="/?mid=forum&amp;category=195523&amp;act=dispForumContent" target="_blank">http://forum.cubrid.org</a>/.</p>]]></description>
                        <pubDate>Thu, 30 Dec 2010 10:48:39 -0800</pubDate>
                        <category>java</category>
                        <category>jdbc</category>
                        <category>library</category>
                                </item>
            </channel>
</rss>
