I'm trying to get a count from an ODBC database in Elixir. I can see my result coming back, however, I don't know how to extract the value.
{:ok, conn} = :odbc.connect('DSN=mydsn;UID=myuid;PWD=mypwd', [])
{:selected, _colNames, rows} = :odbc.sql_query(conn, 'select count(*) from mytable')
{:selected, ['COUNT'], [{'182'}]}
How do I get 182 out as an integer?
The closest I got was getting the inner tuple:
hd(rows)
{'182'}
Elixir tuples are stored contiguously in memory and are accessed by index. A tuple literal uses a pair of curly braces {} . The elem/2 function is used to access a data item in a tuple. The length of a tuple can be found with the tuple_size/1 function.
In Elixir and Erlang we use `list ++ [elem]` to append elements.
Lists are a basic data type in Elixir for holding a collection of values. Lists are immutable, meaning they cannot be modified. Any operation that changes a list returns a new list. Lists implement the Enumerable protocol, which allows the use of Enum and Stream module functions.
There are different possible solutions depending whether you are interested in this specific case or in a broader approach.
In this specific instance, as rows
is expected to be a list with a single tuple with a single value, you can take advantage of the pattern matching to extract the value.
{:selected, _, [{count}]} = {:selected, ['COUNT'], [{'182'}]}
From this point count
will match '182'
. However, please note that '182'
is different than "182"
"182" == '182'
false
As explained in the Elixir documentation, '182'
is a char-list whereas "182"
is a String. Therefore you can't use String.to_integer
directly as it will fail.
String.to_integer(count)
** (ArgumentError) argument error
:erlang.binary_to_integer('182')
You first need to use List.to_integer(count)
or alternatively convert it into a String, then cast to an integer.
List.to_integer(count)
182
String.to_integer(to_string(count))
182
This solution may not be applicable directly if the tuple contains more than one value (which means the query returns more than one value as result). However it's a starting point you can adapt to your needs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With