【发布时间】:2017-03-06 19:34:20
【问题描述】:
有没有办法将 MySQL 数据库的日期时间列加载到 Mysql gem 的结果中,该结果可枚举为 Ruby 日期时间对象(不是字符串类型对象)?
例如:
在数据库端,我们有这张表,里面有以下插入:
create table ContentDB.test_table
(
id integer primary key auto_increment,
last_update_date datetime,
value varchar(128)
);
insert into ContentDB.test_table(last_update_date, value) values (sysdate(), 'Some test stuff..');
commit;
在 Ruby 方面,我们有以下代码(作为名为 test.rb 的文件):
require 'rubygems'
require 'mysql'
require 'date'
begin
con = Mysql.new "localhost", "root", "root", "ContentDB"
rs = con.query "select * from test_table"
rs.each_hash do |row|
l_datetime_field = row['last_update_date'].strftime("%Y%m%d%H%M%S")
end
con.close
end
这会出现以下错误:
test.rb:9:in `block in <main>': undefined method `strftime' for "2017-03-06 22:15:17":String (NoMethodError)
我知道我可以将即将到来的“字符串”值显式转换为日期时间对象。
但我相信,不应该是这样。我希望我的行是完全相同的行类型(pl/sql 术语),即每个字段都与数据库列类型对应。也就是说
row['last_update_date']
必须是“日期时间”数据类型。
在不使用 rails 的 ActiveRecord 的情况下,是否有隐含的方式在 Ruby 中实现这一点?
最好的问候,
【问题讨论】:
标签: mysql ruby datetime casting rubygems