官术网_书友最值得收藏!

Exploring data from a SQLite database

SQLite is a relational database that enforces a strict schema. It is simply a file on a machine that we can interact with through Structured Query Language (SQL). There is an easy-to-use Haskell library to send these SQL commands to our database.

In this recipe, we will use such a library to extract all data from a SQLite database.

Getting ready

We need to install the SQLite database if it isn't already set up. It can be obtained from http://www.sqlite.org. On Debian systems, we can get it from apt-get using the following command:

$ sudo apt-get install sqlite3

Now create a simple database to test our code, using the following commands:

$ sqlite3 test.db "CREATE TABLE test \
(id INTEGER PRIMARY KEY, str text); \
INSERT INTO test (str) VALUES ('test string');"

We must also install the SQLite Haskell package from Cabal as follows:

$ cabal install sqlite-simple

This recipe will dissect the example code presented on the library's documentation page available at http://hackage.haskell.org/package/sqlite-simple/docs/Database-SQLite-Simple.html.

How to do it…

  1. Use the OverloadedStrings language extension and import the relevant libraries, as shown in the following code:
    {-# LANGUAGE OverloadedStrings #-}
    
    import Control.Applicative
    import Database.SQLite.Simple
    import Database.SQLite.Simple.FromRow
  2. Define a data type for each SQLite table field. Provide it with an instance of the FromRow typeclass so that we may easily parse it from the table, as shown in the following code snippet:
    data TestField = TestField Int String deriving (Show)
    
    instance FromRow TestField where
      fromRow = TestField <$> field <*> field
  3. And lastly, open the database to import everything as follows:
    main :: IO ()
    main = do
      conn <- open "test.db"
      r <- query_ conn "SELECT * from test" :: IO [TestField]
      mapM_ print r
      close conn
主站蜘蛛池模板: 福贡县| 丹寨县| 河曲县| 双鸭山市| 洛扎县| 缙云县| 石阡县| 会宁县| 嘉善县| 紫阳县| 马尔康县| 莱芜市| 喀喇| 平湖市| 鹤山市| 台北县| 德清县| 金坛市| 揭西县| 山西省| 嵊州市| 金湖县| 襄垣县| 隆尧县| 博客| 玉田县| 克山县| 平谷区| 隆德县| 金昌市| 岑溪市| 茶陵县| 南通市| 平凉市| 永德县| 石城县| 潜山县| 小金县| 嘉鱼县| 涟水县| 城口县|