I have managed to connect my web service to the database, but now whenever I make a request it returns nothing. The database has a couple of rows, but the web service returns zero.
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
I'm pretty sure I am doing the execute, but this is the first time I am using tiny_tds and I am very confused. Thank you for your help.
[EDIT] This is 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] I have modified the code as suggested and it returns a result, but it does not return the data from the database. This is a result:
{"recordsArray":["{\"username\":\"\",\"password\":\"\",\"phone_number\":\"\",\"profile_state\":\"\",\"clasa\":\"\"}"]}
conn.execute(sql)
does not accept a block, it simply returns a result. The proc afterwards is treated by a ruby interpreter as “orphan proc definition” and never gets executed. You might try to put puts 'I am here'
inside it and see it is never called.
The solution would be to iterate the result:
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