我正在使用 PG gem 将数据插入到我的 Postgres 数据库中,但是,当我尝试插入包含时间戳的数据时,数据库没有得到更新。这是我从 IRB 运行的代码:
:001 > require 'pg'
=> true
:002 > conn = PGconn.open(:dbname => 'my_db')
=> #<PG::Connection:0x8fa4a94 @socket_io=nil, @notice_receiver=nil, @notice_processor=nil>
:003 > conn.prepare('statement1', 'insert into sites (url, note, type, last_viewed) values ($1, $2, $3, $4)')
=> #<PG::Result:0x8f3c19c @connection=#<PG::Connection:0x8fa4a94 @socket_io=nil, @notice_receiver=nil, @notice_processor=nil>>
:004 > conn.exec_prepared('statement1', [ 'digg.com', 'news site', 3, date_trunc('second', #{conn.escape_string(current_timestamp)) ] )
:005 >
我相信这个问题与单引号的转义方式有关。我开始包含 PG gem 的escape_string
方法是因为我在第 4 行运行我以前版本的代码时收到的错误消息。
004 > conn.exec_prepared('statement1', [ 'digg.com', 'news site', 3, date_trunc('second', current_timestamp) ] )
NameError: undefined local variable or method `current_timestamp' for main:Object
from (irb):4
from /home/user/.rvm/rubies/ruby-2.0.0-p247/bin/irb:16:in `<main>'