ruby(rails) 程序如何 连接 各种远程数据库?

Python014

ruby(rails) 程序如何 连接 各种远程数据库?,第1张

在使用Cookie.find等操作的时候,就会连接到database.yml中monitor_spider配置的数据库上操作。以前一直都这么用,没发现什么不妥。最近一个项目,由于启动的进程比较多,老是碰到数据库连接池链接获取超时的错误。

通过MySQL Client用命令:show processlist发现数据库连接数量一直居高不下,轻轻松松就上2k+的连接。通过读Rails框架的connection_pool.rb文件代码,发现在各模型中用establish_connection连接数据库会造成很大的问题。文件中类ConnectionHandler的establish_connection方法代码如下:Ruby代码 def establish_connection(name, spec) @connection_pools[name] = ConnectionAdapters::ConnectionPool.new(spec) end def establish_connection(name, spec)

@connection_pools[name] = ConnectionAdapters::ConnectionPool.new(spec)

读取csv

文件中读取:一次读入全部(设置headers使 CSV#shift() 以CSV::Row对象返回而不是数组;使

require'csv'CSV#read() 返回 CSV::Table 对象而不是数组)CSV.read('test.csv')#=>Array#headers默认为false,如果设置为true,csv的第一行将被视为标题CSV.read('test.csv',headers:true)#=>CSV::Table#headers设置为数组,这个数组将被作为标题CSV.read('test.csv',headers:[1,2,3,4,5])#headers设置为字符串,这个字符串内容将被作为标题CSV.read('test.csv',headers:"1,2,3,4,5")

​ 文件中读取:一次读入一行

#由于headers配置,返回类型发生变化(这个方法默认为第一行是标题,不会进行返回)CSV.foreach'test.csv'do|row|puts row.class#=>ArrayendCSV.foreach('test.csv',headers:true)do|row|puts row.class#=>CSV::Rowend#return_headers:true 返回标题CSV.foreach('test.csv',return_headers:true)do|row|p row#=>返回Arrayend

​ 字符串中读取:一次读取一行

CSV.parse("CSV,data,String")do|row|# use row here...end

​ 字符串中读取:全部读取

CSV.parse("CSV,data,String")#[]方法需要返回的类型为CSV::ROW所以设置参数headers:truecontent = File.read('data.csv') csv = CSV.parse(content,headers:true) sum =0csv.eachdo|row|sum += row['id'].to_iendputs sum