【问题标题】:How to remove quotes from dictionary value string dynamically如何从字典值字符串中动态删除引号
【发布时间】:2020-05-16 00:32:02
【问题描述】:

我有一本字典,例如:d = {'table': 'db_schema.foo', 'column': 'bar'}。我想在从所有值中删除引号后传递这本字典。所以我想动态获取{'table': db_schema.foo, 'column': bar}

详情:

我正在尝试在连接后将运行动态查询传递给 exasol。我在这里使用 pyexasol 并尝试 execute() 。我正在尝试执行简单的查询,例如:

SELECT * 
FROM db_schema.foo
WHERE bar >= 0

如果我提供字典 d,那么执行的查询是:

SELECT * 
FROM 'db_schema.foo'
WHERE 'bar' >= 0

并导致错误。所以我想从所有值中删除引号。我已经尝试过{k:v.strip("\'") for k, v in d.items()} 等,但还没有成功。

请求的代码:

foo_query = '''select *
                from {app_table}
                where {col} >= '2020-01-01'
                limit 10;'''
foo_param={'app_table': 'src.application',
             'col': 'createdat'}
foo_results = exasol.runQueryExaParams(query=foo_query, query_param=foo_param)
foo_results1 = exasol.runQueryExaParams(query=foo_query, query_param={k:v.strip("\'") for k, v in foo_param.items()})

其中 exasol 是基于 pyexasol 构建的类,仅具有连接参数。类的相关方法有:

    def runQueryExaParams(self, query, query_param):
        self.conn = pyexasol.connect(
            dsn=self.__dsn, user=self.__user, password=self.__password, encryption=True)
        res = self.conn.export_to_pandas(query, query_param)
        self.conn.close()
        res.columns = res.columns.str.lower()
        return res

在这两种情况下,我都会遇到相同的错误:

pyexasol.exceptions.ExaQueryError: 
(
    message     =>  syntax error, unexpected simple_string_literal [line 3, column 22] (Session: )
    dsn         =>  
    user        =>  
    schema      =>  
    code        =>  42000
    session_id  =>  
    query       =>  EXPORT (
select *
                from 'src.application'
                where 'createdat' >= '2020-01-01'
                limit 10
) INTO CSV
AT 'https://1.2.3.4' FILE '000.csv'
WITH COLUMN NAMES
)

【问题讨论】:

  • 引号只是字典表示的一部分,它们实际上并不存在于值中。请为execute 调用显示您的实际代码。
  • 发布您收到的代码和完整的错误消息。字典中显示的引号正是 Python 表示字符串的方式。
  • 你需要阅读SQL FORMATTING。特别是!i, "验证标识符并将其不带引号。它允许您传递小写标识符以查询大写命名表,同时保持其“安全”。它是标识符占位符的“方便”版本。”

标签: python python-3.x dictionary exasol


【解决方案1】:

正如我在评论中所说,您需要阅读SQL FORMATTING

话虽如此,您需要将代码更改为如下所示:

query = '''
    SELECT *
    FROM {app_table!q}
    WHERE {col!i} >= '2020-01-01'
    LIMIT 10;
'''

query_param = {
    'app_table': ('src', 'application'),
    'col': 'createdat'
}

results = exasol.runQueryExaParams(
    query=query,
    query_param=query_param
)

如文档所示,上面的代码将产生如下查询:

SELECT *
FROM "src"."application"
WHERE createdat >= '2020-01-01'
LIMIT 10;

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2020-06-10
    • 2022-01-01
    • 2011-05-12
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多