4

我正在尝试将 ruby​​ 中的准备好的语句与 pg gem 一起使用。这就是我的陈述的样子

conn.prepare("insert_values", "insert into " + objectName + "(" + headerStr + ") values (" + prep_values + ")")  
conn.exec_prepared("insert_values", arr)

我不断收到错误

准备好的语句 insert_values 已经存在。

我该如何解决??谢谢

4

2 回答 2

8

尝试运行:

conn.exec("DEALLOCATE name_of_prepared_statement")

在您的示例中:

conn.exec("DEALLOCATE insert_values")

简单的测试,它在我的 irb 中工作:

1.8.7 :001 > require 'rubygems'
  => true
1.8.7 :002 > require 'pg'
  => true
1.8.7 :003 > conn = PGconn.connect(:host => 'localhost', :port => 5912, :user => 'test', :dbname => 'test' )
  => #<PGconn:0x7fe6ac703970> 
1.8.7 :005 > conn.prepare("insert_values", "select * from data where id < $1")
  => #<PGresult:0x7fe6ac6b2e58> 
1.8.7 :006 > conn.prepare("insert_values", "select * from data where id < $1 and id >   $2")
  PGError: ERROR:  prepared statement "insert_values" already exists

  from (irb):6:in 'prepare'
  from (irb):6
1.8.7 :007 > conn.prepare("insert_values", "select * from data where id < $1")
  PGError: ERROR:  prepared statement "insert_values" already exists

  from (irb):7:in 'prepare'
  from (irb):7
1.8.7 :008 > conn.exec("DEALLOCATE insert_values")
  => #<PGresult:0x7fe6ac6738c0> 
1.8.7 :009 > conn.prepare("insert_values", "select * from data where id < $1")
  => #<PGresult:0x7fe6ac665fe0> 
1.8.7 :010 > conn.exec_prepared("insert_values",[200])
  => #<PGresult:0x7fe6ac65d188> 
1.8.7 :011 > conn.exec("DEALLOCATE insert_values")
  => #<PGresult:0x7fe6ac654df8> 
1.8.7 :012 > conn.exec_prepared("insert_values",[200])
  PGError: ERROR:  prepared statement "insert_values" does not exist

  from (irb):12:in 'exec_prepared'
  from (irb):12
于 2012-12-20T10:29:20.087 回答
3

这是重用的更好方法prepare(),避免prepared statement "my_statement" already exists

sql = "select * from my_table where id = $1"
begin
  ActiveRecord::Base.connection.raw_connection.prepare('my_statement', sql)
rescue PG::DuplicatePstatement => e
end

pg_result = ActiveRecord::Base.connection.raw_connection.exec_prepared('my_statement', [my_table_id])
于 2016-01-06T05:03:50.277 回答