python - 如何动态删除字典值字符串中的引号

标签 python python-3.x dictionary exasol

我有一个字典,例如: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
)

最佳答案

正如我在评论中所说,您需要阅读 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;

希望对您有所帮助。

关于python - 如何动态删除字典值字符串中的引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59985238/

相关文章:

c++ - 在类中存储固定的已知数据(c++)

python - 如何在 forms.Form 子类上动态设置 models.ModelChoiceField 的查询集

python - 在python中读取原始二进制数据并将其转换为ascii

python - 将列表元素与列表列表元素进行比较并有条件地创建新列表

c++ - 无法使用 end() 获取 map 的第二个字段

Python3 : create selective copy of dictionary as a new dictionary

python Pycharm : Describe Dataframe not Shown

python - POS 标记的性能缓慢。我可以做一些预热吗?

python-3.x - 用 % 按数字拆分 pandas 列

python-3.x - 谷歌云 python 项目有本地主机错误