【问题标题】:Is it possible to put variables into my query?是否可以将变量放入我的查询中?
【发布时间】:2016-09-13 12:52:31
【问题描述】:

我有一个使用 Ruby On Rails 的 ActiveRecord 的 postgresql 查询

my_table.location = ActiveRecord::Base.connection.execute("UPDATE my_table SET location = ST_SetSRID(ST_MakePoint(my_table.longitude, my_table.latitude), 4326)::geography")

我想像这样将变量放入我的查询中,因为我不想使用数据库中的经度和纬度列,而是使用一些包含经度和纬度值的变量。

my_table.location = ActiveRecord::Base.connection.execute("UPDATE my_table SET location = ST_SetSRID(ST_MakePoint((?), (?), 4326)::geography"), longitude, latitude)

我找不到使它起作用的方法,但您应该了解其背后的想法。是否存在一些在我的查询中使用变量的方法?

【问题讨论】:

标签: ruby-on-rails ruby database postgresql activerecord


【解决方案1】:

是的,您可以轻松做到。确保在将查询传递给数据库之前对其进行清理。我这里使用了quote的方法。另外,请阅读 KNejad 的评论了解更多详情

 conn = ActiveRecord::Base.connection
 @from = conn.quote(params["from"))
 @to = conn.quote(params["to"))

 
 @from_date = Time.parse(@from).to_date.beginning_of_day
 @till_date = Time.parse(@to).to_date.end_of_day
          
 sql = "select abc.sss,im.lat,
 im.long from  users as rq JOIN  images as 
 im ON rq.id= im.imageable_id where  rq.created_at  
 BETWEEN '#{@from_date}' AND '#{@till_date}' ;" 
  
 response = ActiveRecord::Base.connection.execute(sql)
          

【讨论】:

  • 你使用的是和下面建议的一样的东西吗?
  • 您了解如何在您的 sql 查询中使用变量吗?我已经向您展示了我的示例之一
  • '#{longitude}' 你可以使用它,如果它不起作用然后使用 #{longitude}
  • 是的,谢谢,我想我理解得很好,正在尝试适应我的情况,之后会标记为已回答。
  • 这在这种情况下可以正常工作,但您应该注意,如果 @from_date 直接来自用户,这很容易受到 SQL 注入攻击。因此,您应该始终确保在将数据传递到数据库之前对其进行清理(例如,通过将其解析为日期对象,就像这个答案所做的那样)
【解决方案2】:

这是您的用例的解决方案,我认为需要检查 longitude.present? and latitude.present?

my_table.location = ActiveRecord::Base.connection.execute("UPDATE my_table SET location = ST_SetSRID(ST_MakePoint(#{longitude}, #{latitude}, 4326)::geography")) if longitude.present? and latitude.present?

【讨论】:

    猜你喜欢
    • 2022-11-24
    • 2019-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多