Skip to content

Instantly share code, notes, and snippets.

@saboyutaka
Last active May 21, 2018 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saboyutaka/fcd97cd289096bfe0fd63916a11f7fbb to your computer and use it in GitHub Desktop.
Save saboyutaka/fcd97cd289096bfe0fd63916a11f7fbb to your computer and use it in GitHub Desktop.
MySQLにアクセスしてデータを取得し表示する
require 'sinatra'
require 'sinatra/reloader'
require 'mysql2'
require 'mysql2-cs-bind'
# Mysqlドライバの設定
db = Mysql2::Client.new(
host: 'localhost',
port: 3306,
username: 'root',
password: '',
database: 'sample',
reconnect: true,
)
set :public_folder, File.dirname(__FILE__) + '/public'
get '/' do
@title = 'hoge'
erb :index
end
get '/hello' do
erb :hello
end
get '/fruits/' do
@fruits = ['Apple', 'Banana', 'Lemon', 'Meron', 'Strawberry']
erb :fruits
end
get '/infos' do
# @infos = [{
# name: 'saboyuta',
# age: 30
# },{
# name: 'gakeo',
# age: 27
# }]
@infos = db.xquery("SELECT * From infos")
erb :infos
end
get '/infos/:id' do |id|
# @info = [{
# name: 'saboyuta',
# age: 30
# }]
@info = db.xquery("SELECT * From infos WHERE id = #{id}").to_a.first
erb :info
end
<h1>Info</h1>
<p>名前は、<%= @info["name"] %></p>
<p>年齢は、<%= @info["age"] %></p>
<h1>Info</h1>
<% @infos.each do |info| %>
<p>名前は、<%= info["name"] %></p>
<p>年齢は、<%= info["age"] %></p>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment