修改ruby代码以使用Postgresql

时间:2013-01-21 01:22:21

标签: ruby postgresql sqlite pg

我以前使用sqlite3作为我的ruby代码,它适用于以下代码

def existsCheck( db, id )
    temp = db.exec( 'SELECT 1 WHERE EXISTS(
        SELECT 1
        FROM Products
        WHERE promoID = ?
    ) ', [id] ).length > 0
end


def writeDB( db, product )
    db.exec( 'INSERT INTO Products ( promoID, name, price, shipping, condition, grade, included, not_included, image, time_added )
                        VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', [product.promoID, product.name, product.price, product.shipping, product.condition, product.grade, product.included, product.notIncluded, product.image, product.time] )
end

Postgresql不支持“?”的想法或者我做错了什么?

1 个答案:

答案 0 :(得分:0)

来自fine PG::Connection manual

  

- (PG::Result) exec(sql[, params, result_format ])
  - (Object) exec(sql[, params, result_format ]) {|pg_result| ... }
  [...]
  PostgreSQL绑定参数在SQL查询中表示为$1$1$2等。 params数组的第0个元素绑定到$1,第1个元素绑定到$2,等等。nil被视为NULL

所以你想在PostgreSQL中使用带编号的占位符:

def existsCheck( db, id )
    temp = db.exec( 'SELECT 1 WHERE EXISTS(
        SELECT 1
        FROM Products
        WHERE promoID = $1
    ) ', [id] ).to_a.length > 0
    # You'll also need to .to_a the result before you can
    # treat it as an array...
end