Last active
May 21, 2018 13:16
-
-
Save saboyutaka/fcd97cd289096bfe0fd63916a11f7fbb to your computer and use it in GitHub Desktop.
MySQLにアクセスしてデータを取得し表示する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h1>Info</h1> | |
<p>名前は、<%= @info["name"] %></p> | |
<p>年齢は、<%= @info["age"] %></p> | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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