This must be something very basic. I’m not familiar with the syntax, and this is my first most difficult problem. connection below returns something of type IO Connection – but I don’t understand how IO and Connection are connected / what does it mean. If you can, please tell what is the purpose of IO in this operation and how can I loose it.
{-# LANGUAGE OverloadedStrings #-}
import Database.MySQL.Simple
-- This returns `IO Connection'
connection :: Connection
connection = do
c <- connect defaultConnectInfo
{ connectPassword = "password",
connectDatabase = "database" }
return c
-- Possibly need to do something to `c', but don't know what
first_table :: IO String
first_table = do
[Only i] <- query_ connection "show tables"
return i
test_query :: IO Int
test_query = do
[Only i] <- query_ connection "select 2 + 2"
return i
However, my final goal was to find a way to only connect to the database once, store the connection handle somewhere and reuse it when first or second functions are called. I’m nowhere near understanding how that may be done (in Erlang, for example, I’d need to open a separate process and wait for messages requesting the connection, which is extremely cumbersome and uncomfortable – so I hope, I wouldn’t need to go through anything like that…).
Thanks in advance.
EDIT:
{-# LANGUAGE OverloadedStrings #-}
import Database.MySQL.Simple
-- I need, instead of this function something that only connects once to the databse.
connection :: IO Connection
connection = do
c <- connect defaultConnectInfo
{ connectPassword = "password",
connectDatabase = "database" }
return c
first_table :: IO String
first_table = do
c <- connection
[Only i] <- query_ c "show tables"
return i
test_query :: IO Int
test_query = do
c <- connection
[Only i] <- query_ c "select 2 + 2"
return i
Think of connection as if it was, well, let it be Java for a change:
public Connection getConnection() {
if (connection == null) connection = /* JDBC does it's dirty job
and creates connection handle */
return connection;
}
IOis parametrized type (called type constructor in Haskell or generic in C#/Java). In this caseStringis its type argument.IO Stringin Haskell would be written asIO<String>in Java/C#/C++.