【问题标题】:How to generate SQL query for postgres (Redshift) without connection?如何在没有连接的情况下为 postgres (Redshift) 生成 SQL 查询?
【发布时间】:2017-10-11 14:45:29
【问题描述】:

我想构建 SQL 查询以传递给spark-redshift 读者的“查询”选项。我正在尝试使用 psycopg2,所以我做了这样的事情:

from psycopg2 import sql

query = sql.SQL(
    "select * from {} where event_timestamp < {}"
).format(
    sql.Identifier("events"),
    sql.Literal(datetime.now())
).as_string()

但它告诉我需要将上下文(连接或光标)传递给as_string()。我不能,因为我没有任何联系。

在这种情况下我应该使用纯字符串格式并进行一些转义吗?

或者有什么方法可以在那里传递一些模拟上下文?为什么它需要连接来构建查询字符串? SQL 查询是否会因连接而异?

【问题讨论】:

    标签: python sql postgresql amazon-redshift psycopg2


    【解决方案1】:

    我不熟悉 spark,但如果他们没有某种 sql 支持,我会感到惊讶。另一种选择是像sqlbuilder 这样的轻量级包。

    如果你真的想使用 psycopg,我建议看看他们如何使用模拟进行单元测试 -- psycopg2's ConnectingTestCase

    class ConnectingTestCase(unittest.TestCase):
        """A test case providing connections for tests.
    
        A connection for the test is always available as `self.conn`. Others can be
        created with `self.connect()`. All are closed on tearDown.
    
        Subclasses needing to customize setUp and tearDown should remember to call
        the base class implementations.
        """
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-28
      • 2010-10-01
      • 2019-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多