databasehaskellsqlitehdbc

Add multiple entries from within a program to an SQLite3 database with HDBC / Haskell


I'm trying to use Database.HDBC and Database.HDBC.Sqlite3.

To add tables to an SQLite3 database, this is the kind of command I'd enter into GHCI:

run conn "CREATE TABLE table1 (a INTEGER)" []

I'd like to now use a list of strings to add table names to a database from within my program.

This is the variable I'm working with:

tables = ["CREATE TABLE t1 (a INTEGER)","CREATE TABLE t2 (a INTEGER)",..]

tables is passed to a function I made called addTables:

addTables xs = [ run conn x [] | x <- xs ]

But my addTables function returns this error:

<interactive>:199:1:
    No instance for (Show (IO Integer))
      arising from a use of `print'
    Possible fix: add an instance declaration for (Show (IO Integer))
    In a stmt of an interactive GHCi command: print it

I suspect Haskell doesn't like list comprehensions that don't print anything?

Any help or suggestions would be greately appreciated.


Solution

  • No, the problem is that IO actions can't be printed. See, you've only constructed a list of actions, rather than running them.

    Try this instead:

    addTables xs = sequence [run conn x [] | x <- xs]
    

    or, equivalently:

    addTables xs = mapM (\x -> run conn x []) xs
    

    If you don't care about the results, mapM_ is slightly more efficient.