How to use MySQL with Erlang
First, you'll need to install the MySQL ODBC driver if you haven't already.
sudo aptitude install unixodbc
Check the installation by performing command:
odbcinst j
which lists the ODBC's configuration files location.
Now we install the driver we want to use (for the start I was using the sqlite3 ODBC driver, but it was not working with
erlang properly). Let's say mysql:
sudo aptitude install libmyodbc
as we have the ODBC driver for our database, we have to ensure it's installed, by issuing:
odbcinst q d
Which should give something like
$ odbcinst q d
[MySQL]
If, however, you get an error such as
odbcinst: SQLGetPrivateProfileString failed with .
dont panic. It just means that the SQL driver was not automatically installed, hence you will have to install it manually.
Adding a driver to the system's configuration
In my case the libmyodbc hasn't installed itself to the /etc/odbcinst.ini, so I had to add that section by hand
(/etc/odbcinst.ini):
[MySQL]
Description = MySQL ODBC Driver
Driver = /usr/lib/odbc/libmyodbc.so
Setup = /usr/lib/odbc/libmyodbc.so
UsageCount = 1
After which we now '''add a datasource DSN'''
Next, edit the file ~/.odbc.ini and put in the appropriate values
[mysqldb]
Description=Mysql database
Driver=MySQL
Database=test
User=kubek2k
Password=kubek2k
Server=localhost
of course - be sure that the user exists and the user has rights to use it :).
Example
Here's the SQL script I used to create my test database:
CREATE DATABASE `test`;
CREATE TABLE `test`.`test_table`
(
`id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`first_name` VARCHAR(45) NOT NULL,
`last_name` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`)
)
ENGINE = InnoDB;
INSERT INTO `test`.`test_table`
(
`first_name`,
`last_name`
)
VALUES
('Matt', 'Williamson'), ('Matt', 'Williamson2'), ('Matt', 'Williamson3');
And here's the code to connect and query in erlang:
application:start(odbc).
ConnString = "DSN=mysqldb".
{ok, Conn} = odbc:connect(ConnString, []).
Results = odbc:sql_query(Conn, "SELECT * FROM test_table").
This is what my interactive session looks like:
arthur@badger:~$ erl
Erlang (BEAM) emulator version 5.6.3 [source] [smp:2] [asyncthreads:0] [kernel
poll:false]
Eshell V5.6.3 (abort with ^G)
1> application:start(odbc).
ok
2> ConnString = "DSN=mysqldb".
"DSN=mysqldb"
3> {ok, Conn} = odbc:connect(ConnString, []).
{ok,<0.40.0>}
4> Results = odbc:sql_query(Conn, "SELECT * FROM test_table").
{selected,["id","first_name","last_name"],
[{1,"Matt","Williamson"},
{2,"Matt","Williamson2"},
{3,"Matt","Williamson3"}]}
5>
BREAK: (a)bort (c)ontinue (p)roc info (i)nfo (l)oaded
(v)ersion (k)ill (D)btables (d)istribution
a
arthur@badger:~$
That's it folks! Hope you got it well.
© Arthur Buliva