【问题标题】:pass a string variable into a gql query将字符串变量传递给 gql 查询
【发布时间】:2012-06-25 22:13:56
【问题描述】:

到底如何使用 python 将字符串变量传递给 GQL?我可以在 SQL 中做的很好,但它只是不工作。这是我所拥有的:

personalposts = db.GqlQuery("select * from PersonalPost where user_id = %s order by created desc limit 30" % user_id)

这让我很生气,但我觉得应该很简单。

谢谢!

【问题讨论】:

    标签: python google-app-engine google-cloud-datastore gql


    【解决方案1】:

    这应该可行:

    personalposts = db.GqlQuery("select * from PersonalPost where user_id =:1 order by created desc limit 30",user_id)
    

    GqlQuery 语法示例:

    q = GqlQuery("SELECT * FROM Song WHERE composer = 'Lennon, John'")
    
    q = GqlQuery("SELECT __key__ FROM Song WHERE composer = :1", "Lennon, John")
    
    q = GqlQuery("SELECT * FROM Song WHERE composer = :composer", composer="Lennon, John")
    

    来源: https://developers.google.com/appengine/docs/python/datastore/gqlqueryclass

    【讨论】:

    • 啊太棒了!所以 :1 符号只是说这是 GQL 之后列出的第一个参数?
    【解决方案2】:

    参数可以通过位置或名称绑定,更多信息请查看GqlQuery 类文档。

    所以你可以这样做

    personalposts = db.GqlQuery("select * from PersonalPost where user_id = :1 order by created desc limit 30", user_id)
    

    personalposts = db.GqlQuery("select * from PersonalPost where user_id = :id order by created desc limit 30", id = user_id)
    

    【讨论】:

      【解决方案3】:

      创建这样的查询:

      query = PersonalPost.all()
      query.filter('user_id', user_id)
      query.order('-created')
      

      或使用:在 '%s' 周围加上单引号!!

      personalposts = db.GqlQuery("select * from PersonalPost where user_id = '%s' order by created desc" % user_id) 
      

      【讨论】:

      • 这两种方法中的哪一种在技术上更好?我可以让两者都工作。一个比另一个快吗?
      • 我现在已经尝试过了,你现在实际上需要跳过单引号,只需将 %s 放在双引号后的变量结束(也没有逗号)。
      猜你喜欢
      • 2017-11-15
      • 2019-02-15
      • 1970-01-01
      • 2015-12-25
      • 2020-06-16
      • 2019-01-04
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      相关资源
      最近更新 更多