我已设法将我的Web服务连接到数据库,但现在每当我发出请求时它都不返回任何内容。数据库有几行,但Web服务返回零。
get '/all_users/' do
conn = TinyTds::Client.new(username: 'nicole', password: 'pass', dataserver: 'Nikki-PC\Mydatabase', database: 'Thedatabase')
recordsArray = "{\"clientList\":["
clientArray = Array.new
sql = 'select * from dbo.ServerUsers'
records = conn.execute(sql) do |record|
client = AndroidtableClientsSearch.new(record[0], record[1], record[2], record[3], record[4])
clientArray << client.to_s
end
recordsArray << clientArray.join(',')
recordsArray << "]}"
recordsArray
end
我很确定我正在执行,但这是我第一次使用tiny_tds而且我很困惑。 谢谢你的帮助。
[编辑] 这是AndroidClientsSearch:
class AndroidtableClientsSearch
def initialize(username, password, phone_number, profile_state, clasa)
@username = username
@password = password
@phone_number = phone_number
@profile_state = profile_state
@clasa = clasa
end
def to_s
{ :username => "#{@username}", :password => "#{@password}", :phone_number => "#{@phone_number}", :profile_state => "#{@profile_state}", :clasa =>"#{@clasa}"}.to_json
end
end
[UPDATE] 我已根据建议修改了代码并返回结果,但它不会从数据库返回数据。 这是一个结果:
{&#34; recordsArray&#34;:[&#34; {\&#34;用户名\&#34;:\&#34; \&#34; \&#34;密码\& #34;:\&#34; \&#34; \&#34; PHONE_NUMBER \&#34;:\&#34; \&#34; \&#34; profile_state \&#34 ;: \&#34; \&#34; \&#34; clasa \&#34;:\&#34; \&#34;}&#34;]}
答案 0 :(得分:1)
conn.execute(sql)
不接受块,只返回结果。之后的proc被ruby解释器视为“孤立的proc定义”,永远不会被执行。您可能会尝试将puts 'I am here'
放入其中并查看它永远不会被调用。
解决方案是迭代结果:
get '/all_users/' do
conn = TinyTds::Client.new(...)
sql = 'select * from dbo.ServerUsers'
# ⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓ iterate!!!
records = conn.execute(sql).each_with_object([]) do |record, memo|
client = AndroidtableClientsSearch.new(*5.times.map { |i| record[i] })
memo << client.to_s
end
require 'json'
JSON.dump(clientList: records)
end