web 2.0

Using Ruby with SQL Server

Update: I have created an up-to-date tutorial that shows how to use Ruby on Rails with SQL 2008. It is written from the perspective of a .NET Developer and tries to draw comparisons between ASP.NET MVC with LINQ and Ruby on Rails with ActiveRecord.


In the computer world most people seem to be die-hard Windows or die-hard Linux. From a programmers perspective, each platform seems to have a core set of technologies that are associated with it. If you are a web developer working on the Windows platform you are probably going to build solutions using SQL hosting server and .NET. If you are working in a Linux shop you may be more inclined to use MySQL and Ruby.

In my case, I like Windows but I am intrigued by Ruby. I want to write Ruby apps that run on Windows and talk to SQL Server. So I started the challenge the same way most people do. I Googled for some sample code. Unfortunately, most of the snippets I found on the Internet were based on Linux and MySQL. Now I could have copped out and used IronRuby (Microsoft's interpretation of Ruby) but the thought of it made me feel cheap. I really wanted to use the language in its truest form. Eventually I figured out the process. Here it is:

  1. Install Ruby on Windows. There is a one-click installer which you can download here.
  2. Install the Ruby-DBI package. There is a great outline of the process here. The hardest part is making sure that you put the ADO.rb file in the proper folder.

Once the installation is done you can open up your favorite editor and start writing some code. The first step is to include the DBI module. The Ruby DBI module is the library that you use to access the database server. Now it is just a matter of creating your database connection and executing some SQL. The end result is this chunk of code:

require 'dbi'

oConn = DBI.connect('DBI:ADO:Provider=SQLNCLI;Data Source="sqlserver01";Integrated Security=SSPI;Initial Catalog=master')
sth = oConn.execute("SELECT name * FROM sys.databases")
rows = sth.fetch_all
col_names = sth.column_names
sth.finish
DBI::Utils::TableFormatter.ascii(col_names, rows)

Here are the results:

+-----------------------------+ name +-----------------------------+
master
tempdb
model
msdb
AdventureWorks

 

Not bad for a few minutes of tinkering! Now that the database connectivity issue is solved I can start experimenting with ActiveRecord. I also discovered the rubydotnet project recently which gives you the ability to utilize the .NET framework from Ruby. I do not know if this has any real world applications yet but it just looks like it would be fun to try.

blog comments powered by Disqus