Tuesday, August 9, 2011

Ruby Tutorial: SQL Query to Console i.e. TinyTDS in Action

So a previous post talked about using TInyTDS as a means to connect to your database.  Now we actually want to make a query and use it.  The first thing I did when I got it working, was figure out how I could emulate SQL Server Management Studio and make a query and display it.  So here is my code: 

  1. sql = "SELECT * FROM Whatever"
  2. client = TinyTds::Client.new(:username => "myUsername", :password => "myPassword", :dataserver => "myServer", :database => "myDatabase")
  3. result = client.execute(sql)
  4. results = result.each(:symbolize_keys => true, :as => :array, :cache_rows => true, :empty_sets => true) do |rowset| end
  5. #THIS IS TO OUTPUT IT TO THE CONSOLE
  6. for i in (0..result.fields.length)
  7.   printf("%14s", result.fields[i])
  8. end
  9. for j in (0...result.affected_rows)
  10.   puts ""
  11.   for i in (0...result.fields.length)
  12.     printf("%14s",results[j].at(i))
  13.   end
  14. end

1.  This is your SQL Statement, pretty self-explanatory.  If you need help with SQL, a great place to start is here
2.  This is where the magic happens, logging into and connecting to the database.  This was the simplest gem I could find to connect to the database, we use SQL Server (fyi). 
3.  Also very readable, if you need help with what 'execute' does, you can read about TinyTDS's syntax here.  Basically it runs the sql query. 
4. 
6-8.  This will print out the column headers from the table you just created. 
9-14.  This will print out each row, one by one. 


This post is in the process of being written

3 comments:

  1. This was incredibly helpful. Thanks!

    ReplyDelete
  2. How did you find out about :symbolize_keys :as :cache_rows and :empty_sets?

    ReplyDelete