我正在尝试将我的Ruby文件中的所有信息传输到Postgres数据库中。当我没有数组列时,我能够传输信息,所以我假设我得到的错误消息是因为我试图添加的数组列。我得到的错误信息是:
in `exec_prepared': ERROR: missing dimension value (PG::InvalidTextRepresentation)
以下是我用来将我的Ruby文件连接到Postgres数据库的代码:
require 'pg'
class Postgres
# Create the connection instance. Scraping is the name of the database I am adding this information to
def connect
@conn = PG.connect(:dbname => 'scraping')
end
# Create our venue table
def createVenueTable
@conn.exec("CREATE TABLE venues (venue_number varchar(15) UNIQUE,...,img_array varchar[]);")
end
...
def prepareInsertVenueStatement
@conn.prepare("insert_venue", "insert into venues(venue_number,...,img_array) values ($1,...,$24)")
end
# Add a venue with the prepared statement.
def addVenue(venue_number,...,img_array)
@conn.exec_prepared("insert_venue", [venue_number,...,img_array])
end
end
当我检查我的Postgres数据库时,会生成img_array列,但是,我无法填充它。请帮忙!谢谢。
答案 0 :(得分:-1)
我建议使用序列化来处理这个,这样你实际上只是在编写一个字符串而不是一个实际的数组。
require 'pg'
require 'yaml'
class Postgres
# Create the connection instance. Scraping is the name of the database I am adding this information to
def connect
@conn = PG.connect(:dbname => 'scraping')
end
# Create our venue table
def createVenueTable
#changed img_array to a varchar(8000) for storing serialized Array
@conn.exec("CREATE TABLE venues (venue_number varchar(15) UNIQUE,...,img_array varchar(8000));")
end
...
def prepareInsertVenueStatement
@conn.prepare("insert_venue", "insert into venues(venue_number,...,img_array) values ($1,...,$24)")
end
# Add a venue with the prepared statement.
def addVenue(venue_number,...,img_array)
@conn.exec_prepared("insert_venue", [venue_number,...,serialized(img_array)])
end
#serialize the Object
def serialized(obj)
YAML.dump(obj)
end
#deserialize the Object
def deserialized(obj)
YAML.load(obj)
end
end
抽象用法示例仅显示序列化
a = [1,2,4,5]
serialized = YAML.dump(a)
#=> "---\n- 1\n- 2\n- 3\n- 4\n- 5\n"
YAML.load(serialized)
#=> [1,2,3,4,5]
#Also works on Hash Objects
h = {name: "Image", type: "jpeg", data:[1,2,3,4,5]}
serial = YAML.dump(h)
#=> "---\n:name: Image\n:type: jpeg\n:data:\n- 1\n- 2\n- 3\n- 4\n- 5\n"
YAML.load(serial)
#=> {:name=>"Image", :type=>"jpeg", :data=>[1, 2, 3, 4, 5]}
希望这有助于您解决此问题。
如果需要存储超过8000个字符,可以切换到varchar(MAX)或文本列定义。我建议使用varchar(MAX),因为数据将作为标准varchar存储,直到它超过8000个字符,此时db基本上将它转换为引擎盖下的文本列。