Reputation: 2042
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'}
Upvotes: 6
Views: 1409
Reputation: 176382
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.
Upvotes: 5