2
如何從特定數據庫中獲取特定表的所有表名和行數?使用Rails獲取特定表的所有表名和行數?
結果
Table Name , Row Count , Table Size(MB)
---------------------------------------
table_1 , 10 , 2.45
table_2 , 20 , 4.00
如何從特定數據庫中獲取特定表的所有表名和行數?使用Rails獲取特定表的所有表名和行數?
結果
Table Name , Row Count , Table Size(MB)
---------------------------------------
table_1 , 10 , 2.45
table_2 , 20 , 4.00
@temp_table = []
ActiveRecord::Base.connection.tables.each do |table|
count = ActiveRecord::Base.connection.execute("SELECT COUNT(*) as count FROM #{table}").fetch_hash['count']
size = ActiveRecord::Base.connection.execute("SHOW TABLE STATUS LIKE '#{table}'").fetch_hash
@temp_table << {:table_name => table,
:records => count.to_i,
:size_of_table => ((BigDecimal(size['Data_length']) + BigDecimal(size['Index_length']))/1024/1024).round(2)
}
end
end
ActiveRecord::Base.connection.tables.each do |table|
h = ActiveRecord::Base.connection.execute("SHOW TABLE STATUS LIKE '#{table}'").fetch_hash
puts "#{h['Name']} has #{h['Rows']} rows with size: #{h['Data_length']}"
end
我怎麼能取表的大小? – 2011-04-01 04:59:28
更新了您的更新的答案。 – 2011-04-01 05:09:45
使用InnoDB顯示錶格狀態不會返回精確的表格行。 – 2011-04-01 05:25:30