2013-06-11 75 views
0

我正在使用ruby 1.9.3p429 (2013-05-15 revision 40747) [x86_64-linux]以及這些寶石。我有一個簡單的DBI腳本來顯示DisplayNames,但是腳本的輸出與數據庫中的輸出不匹配。腳本的輸出獲取最後一條記錄並顯示它10次。如何從MSSQL中使用DBI獲取所有記錄

我的DSN指向MSSQL數據庫。

#/usr/bin/env ruby 
require 'rubygems' 
require 'dbi' 

oConn = DBI.connect('DBI:ODBC:DSN','username','password') 
query=oConn.prepare("select top 10 DisplayName from table") 

query.execute 
@rows=query.fetch_all 
puts @rows.size 

@rows.each do |r| 
    puts r["DisplayName"].to_s 
end 

puts "done" 
query.finish 
oConn.disconnect 

安裝的寶石:

*** LOCAL GEMS *** 

actionmailer (3.2.13) 
actionpack (3.2.13, 3.2.3) 
activemodel (3.2.13, 3.2.3) 
activerecord (3.2.13, 3.2.3) 
activerecord-informix-adapter (1.1.1) 
activerecord-odbc-adapter (2.0) 
activerecord-sqlserver-adapter (3.2.10) 
activeresource (3.2.13, 3.2.3) 
activesupport (3.2.13, 3.2.3) 
arel (3.0.2) 
bigdecimal (1.1.0) 
builder (3.0.4, 3.0.0) 
bundler (1.3.5) 
coffee-rails (3.2.2) 
coffee-script (2.2.0) 
coffee-script-source (1.3.3) 
commonjs (0.2.6) 
daemon_controller (1.1.4) 
dbd-odbc (0.2.5) 
dbi (0.4.5) 
deprecated (2.0.1) 
erubis (2.7.0) 
execjs (1.4.0) 
haml (3.1.6) 
hike (1.2.2, 1.2.1) 
i18n (0.6.1, 0.6.0) 
io-console (0.3) 
journey (1.0.4) 
jquery-rails (2.0.2) 
json (1.7.3, 1.5.5) 
less (2.2.2) 
less-rails (2.2.6) 
libv8 (3.3.10.4 x86_64-linux) 
mail (2.5.4) 
mime-types (1.23) 
minitest (2.5.1) 
multi_json (1.7.3, 1.3.6) 
passenger (4.0.4, 4.0.0.rc6) 
polyglot (0.3.3) 
rack (1.4.5, 1.4.1) 
rack-cache (1.2) 
rack-ssl (1.3.3, 1.3.2) 
rack-test (0.6.2, 0.6.1) 
rails (3.2.13) 
railties (3.2.13, 3.2.3) 
rake (10.0.4, 0.9.2.2) 
rdoc (3.12, 3.9.5) 
ruby-informix (0.8.0) 
ruby-odbc (0.99994) 
rubygems-bundler (1.1.1) 
rvm (1.11.3.7) 
sass (3.1.20) 
sass-rails (3.2.5) 
simple_form (2.0.4) 
sprockets (2.2.2, 2.1.3) 
sqlite3 (1.3.6) 
therubyracer (0.10.1) 
thor (0.18.1, 0.14.6) 
tilt (1.4.1, 1.3.3) 
treetop (1.4.12) 
twitter-bootstrap-rails (2.2.6, 2.2.1) 
tzinfo (0.3.37, 0.3.33) 
uglifier (1.2.6) 
will_paginate (3.0.4) 

回答

1
def get_record 
    begin 
     record = CONN.prepare(" SELECT * FROM questions ") 
     record.execute() 
     record.map { |row| printf "ID : %d, description : %s, marks : %d, category : %s \n", row[0], row[1], row[2] , row[3] } 
    rescue DBI::DatabaseError => e 
     puts "Error code : #{e.err}" 
     puts "Error message : #{e.errstr}" 
    end 

end 

CONN是保持 像CONN = Connection.new.create_connection 我沒有DBI連接的連接的常數。這需要DBI gem instollat​​ion以及驅動程序供應商#特定的我正在使用DBD-mysql,因此它的工作正常。

相關問題