質問

I am playing with Sinatra over the weekend to evaluate it for a small wiki site for my company.

The problem I am having, is that we already have an existing MySQL database with all of our information in it, which other processes use, so I can't recreate it and seed it with data, because then I would have the mess of keeping two different databases synced with the same data.

Can anyone give me an example class for connecting to a MySQL database with Sinatra, and how do I pull fields from my existing columns?

This is an example of my table (from create commands):

CREATE TABLE `serverinfo` (
  `DB` CHAR(10) NOT NULL,
  `SERVERNM` CHAR(30) NOT NULL,
  `INSTANCE` CHAR(30) NOT NULL,
  `LOCATION` CHAR(2) NOT NULL,
  `ROLE` CHAR(15) NOT NULL,
  `HOST` CHAR(180) NOT NULL,
  `STATUS` CHAR(1) NOT NULL DEFAULT 'A',
  PRIMARY KEY (`DB`, `SERVERNM`, `INSTANCE`, `LOCATION`, `ROLE`, `HOST`)
)

I am not sure if I can do what I need with Datamapper, so any other suggestion/example would be great. It would also be great if I had an example of pulling from multiple tables in one class.

役に立ちましたか?

解決

Sinatra has no provision for talking to databases. You can use the mysql2 gem to talk to the database, but I'd highly recommend looking at Sequel, which is a very flexible and powerful ORM, which makes it very easy to talk to legacy databases.

Look through the README, and Cheat Sheet and you'll get a good idea of how easy it is to connect to an existing database, without needing to worry about modifying it.

This is untested of course, but it's the basic steps needed to make a connection and retrieve a record from an existing database:

require 'sequel'
DB = Sequel.connect('mysql2://your_DB:credentials@host/table')
foo = DB[:serverinfo].select(:DB, :SERVERNM).where(:STATUS => 'A').first

Wrap the code above inside a get or post handler in Sinatra and it'll retrieve the record. Something like this would get you close:

require 'sequel'
require 'json'

DB = Sequel.connect('mysql2://your_DB:credentials@host/table')

get '/' do
  content_type :json
  foo = DB[:serverinfo].select(:DB, :SERVERNM).where(:STATUS => 'A').first
  foo.to_json # would return the hash to the browser
end

As far as using Datamapper, read the quote at the top of Sequel's main page.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top