Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 无法插入包含PG gem时间戳的数据?_Ruby_Postgresql - Fatal编程技术网

Ruby 无法插入包含PG gem时间戳的数据?

Ruby 无法插入包含PG gem时间戳的数据?,ruby,postgresql,Ruby,Postgresql,我使用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_proce

我使用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 >

问题是你奇怪地混合了Ruby和SQL;例如,
current\u timestamp
是SQL,而
conn.escape\u string
是Ruby。在本例中,我只是将SQL内联到您准备好的语句中:

conn.prepare(
  'statement1',
  %q{
    insert into sites (url, note, type, last_viewed)
    values ($1, $2, $3, date_trunc('second', current_timestamp))
  }
)

这样做非常安全,因为您不需要在SQL中插入任何内容,只需在插入中添加更多SQL即可。

我强烈建议您查看gem。这是一个编写得非常好的ORM,它允许您以与DBM无关的方式与数据库通信,而不必担心SQL的味道。仔细看一遍,了解它能做什么。作者是PostgreSQL的忠实粉丝,所以Sequel肯定能用。@theTinMan我一定会去看看,谢谢你的提示!
conn.prepare(
  'statement1',
  %q{
    insert into sites (url, note, type, last_viewed)
    values ($1, $2, $3, date_trunc('second', current_timestamp))
  }
)