How to select data through ODBC from Elixir?

I can not find any documentation or examples for this. So far I can successfully connect, but I do not know the syntax for selecting and returning data.

:odbc.start() {:ok, conn} = :odbc.connect('DSN=mydsn;UID=myuid;PWD=mypwd', []) :odbc.execute_stmt(conn, 'select count(*) from mytable') :odbc.stop() 

** (UndefinedFunctionError) undefined function :: odbc.execute_stmt / 2 (odbc): odbc.execute_stmt (# PID <0.85.0>, 'select count (*) from mytable')


Update 10/6/2015

I have found how to do this. I believe that I could not find documentation about this for Elixir because Elixir simply passes the pass to the Erlang library.

In any case, it is sql_query , or select_count :

 {:selected, colNames, rows} = :odbc.sql_query(conn, 'select count(*) from mytable') 

{: selected, ['COUNT'], [{'182'}]}

 {:ok, count} = :odbc.select_count(conn, 'select * from mytable') 

{: ok, 182}


Update 10/7/2015

Here is my last code, which I believe is more idiomatic:

 :odbc.start() case :odbc.connect('DSN=mydsn;UID=#{System.get_env("MY_UID")};PWD=#{System.get_env("MY_PASSWORD")}', []) do {:ok, conn} -> case :odbc.sql_query(conn, 'select count(*) from mytable') do {:selected, _colNames, [{count}]} -> IO.puts "count = #{count}" {:error, err} -> {:error, err} end {:error, err} -> {:error, err} end :odbc.stop() 
+6
source share
1 answer

There are a few things here:

1.) I think you want : odbc.sql_query / 2 . Last year, I created a pretty significant application that uses ODBC to communicate with SQLServer, and I used sql_query almost everywhere. I would share the source, but I canโ€™t.

2.) I can not find any documentation for exec_stmt in the official Erlang ODBC docs (v2.11.1), so I think this might be deprecated. I found an example that uses execute_stmt, but arity was four not two. And it seems that the version of ODBC used (judging by the link itself) is quite old - pre v1.0.

3.) In Elixir, we tend to shy away from rebuilding things that have already been built in Erlang if this is not necessary. Since ODBC is already present in Erlang and it works very well, I would suggest that the general guideline is to call Erlang lib from Elixir. Elixir was designed to make Erlang code easier to call.

+2
source

All Articles