【问题标题】:Run sql script from Ruby从 Ruby 运行 sql 脚本
【发布时间】:2010-03-09 15:54:11
【问题描述】:

使用 DBI::DatabaseHandle#execute 或 DBI::DatabaseHandle#prepare 无法运行 sql 脚本(带有多个 sql 语句)。它失败并出现以下错误:

错误:无法在准备好的语句中插入多个命令

我尝试使用 DBI::DatabaseHandle#do 使用“未准备好”的方式(文档说它“直接进入 DBD 的实现”)但它一直抛出相同的错误。

代码sn-p:

require 'dbd/pg'
require 'dbi'

DBI.connect("dbi:pg:database=dbname", db_user, db_password, db_params) do |dbh|
  schema = IO::read(schema_file)
  dbh.do(schema)
end

我正在使用

ruby 1.8.6 (2007-09-24 补丁级别 111) [i386-mswin32]

dbi-0.4.3

dbd-pg-0.3.9

pg-0.9.0-x86-mswin32

谢谢!

【问题讨论】:

    标签: ruby postgresql dbi


    【解决方案1】:

    使用一个函数或只运行多个准备好的查询。

    【讨论】:

    • 为了运行多个准备好的查询,我猜我需要使用一些 sql 解析器来解析 sql 脚本?如何在红宝石中做到这一点?我不明白你使用函数的意义。
    • 我说的是 PostgreSQL 函数,而不是 ruby​​ 函数。
    【解决方案2】:

    使用 DatabaseHandle#do 运行多个查询是 DBD-Pg 中缺少的功能。请参阅 Ruby/DBI 功能 28001

    请注意,DBD-Pg 所基于的原生 postgresql Ruby 驱动程序 Pg 允许运行多个查询。

    例子:

    require 'pg'
    require 'dbd/pg'
    require 'dbi'
    
    # Pg Succeeds
    PGconn.new({:host=>host,:user=>user,:password=>password,:dbname=>dbname}) do |conn|
      conn.exec("select 1; select 1;")
    end
    
    # DBD-Pg Fails with: ERROR: cannot insert multiple commands ...
    DBI::connect("dbi:pg:database=#{dbname};host=#{host};", user, password) do |dbh|
      dbh.do("select 1; select 1;")
    end
    

    【讨论】:

      猜你喜欢
      • 2013-07-29
      • 1970-01-01
      • 1970-01-01
      • 2021-01-17
      • 2013-03-12
      • 1970-01-01
      • 2013-02-18
      • 2012-03-14
      • 1970-01-01
      相关资源
      最近更新 更多