ruby連接mysql2數據庫

require 'rubygems'
require 'active_record'
require 'mysql2'
require 'net/ssh/gateway'
 
gateway = Net::SSH::Gateway.new(
'remotehost.com',
'username'
)
 
# opens a new port on the established gateway
port = gateway.open('127.0.0.1', 3306, 3307)
 
# use cmd line to verify connection over ssh tunnel
# mysql -u root -h 127.0.0.1 --port 3307
 
client = Mysql2::Client.new(
host: "127.0.0.1",
username: 'root',
password: '',
database: 'app_development',
port: port
)
results = client.query("SELECT * FROM projects")
results.each do |row|
p row
end

1. [代碼][Ruby]代碼    

1require "mysql"
2dbc = Mysql.real_connect('127.0.0.1','root','123','test')
3res = dbc.query('select * from users')
4while row = res.fetch_row do
5    puts "#{row[0]},#{row[1]}"
6end
7 
8這個是ruby 用mysqlianjie數據庫

2. [代碼]mysql2連接    

1require 'mysql2'
2client = Mysql2::Client.new(:host => "主機地址", :username => "用戶名",:password=>"密碼",:database=>"數據庫")
3results = client.query("select * from 數據表");
4results.each do |hash|
5  puts hash.map { |k,v| "#{k} = #{v}" }.join(", ")
6end
client.close
 
gateway.shutdown!
 
class Company < ActiveRecord::Base
establish_connection(
:adapter => "mysql2",
:host => "127.0.0.1",
:username => "root",
:password => "",
:database => "app_development",
:port => 3307 # have to specify the forwarded port for this example due to class scope
)
end
puts Company.all.size
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章