Class: Mysql

Inherits:
Object
  • Object
show all
Defined in:
lib/connect_db.rb

Overview

我经常在开发过程中需要链接数据库(在shell环境中)所有我想把这个功能给抽出来使用

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Mysql

初始化



11
12
13
14
15
16
# File 'lib/connect_db.rb', line 11

def initialize *args
 @db = args[0] 
 @ip = args[1] || "127.0.0.1"
 @user = args[2] || "root"
 @password =  args[3] || ""
end

Instance Attribute Details

#dbObject (readonly)

数据库名



6
7
8
# File 'lib/connect_db.rb', line 6

def db
  @db
end

#ipObject (readonly)

数据库名



6
7
8
# File 'lib/connect_db.rb', line 6

def ip
  @ip
end

#passwordObject (readonly)

数据库名



6
7
8
# File 'lib/connect_db.rb', line 6

def password
  @password
end

#userObject (readonly)

数据库名



6
7
8
# File 'lib/connect_db.rb', line 6

def user
  @user
end

Instance Method Details

#change_db(db) ⇒ Object

改变数据库



39
40
41
42
# File 'lib/connect_db.rb', line 39

def change_db db
	@db = db
	connect
end

#connectObject

链接数据库



19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/connect_db.rb', line 19

def connect
	 log_ok "ip=>#{@ip} 数据库=> #{@db} "
	 ActiveRecord::Base.establish_connection({
     :adapter  => "mysql2",
     :database => @db,
     :encoding => "utf8",
     :port     => 3306,
     :host     => @ip,
     :username => @user,
     :password => @password
   	})
	 # log_ok "当前链接的数据库是:#{@db}"
end

#current_dbObject

输出当前链接数据库的信息



34
35
36
# File 'lib/connect_db.rb', line 34

def current_db
	log_ok "当前链接的数据库是:#{@db}"
end