【问题标题】:Python - Use %s in value of config filePython - 在配置文件的值中使用 %s
【发布时间】:2018-05-22 14:18:34
【问题描述】:

我使用一个配置文件(type .ini)来保存我的 SQL 查询,然后我通过它的键得到一个查询。一切正常,直到创建带有参数的查询,例如:

;the ini file

product_by_cat = select * from products where cat =%s

我用:

config = configparser.ConfigParser()
args= ('cat1')
config.read(path_to_ini_file)
query= config.get(section_where_are_stored_thequeries,key_of_the_query)
complete_query= query%args

我得到了错误:

TypeError:字符串格式化期间并非所有参数都转换

所以它尝试在从 ini 文件中检索值时格式化字符串。 我的问题的任何建议。

【问题讨论】:

    标签: sql python-3.x ini


    【解决方案1】:

    你可以像这样使用format函数

    ini 文件

      product_by_cat = select * from products where cat ={}
    

    蟒蛇:

     complete_query= query.format(args)
    

    【讨论】:

      【解决方案2】:

      根据ConfigParser(Python 2 或 Python 3)的版本,您可能需要像这样将% 加倍,否则会引发错误:

      product_by_cat = select * from products where cat =%%s
      

      虽然更好的方法是使用配置解析器的原始版本,但不会解释 % 字符

      config = configparser.RawConfigParser()
      

      【讨论】:

        猜你喜欢
        • 2018-05-08
        • 2022-11-07
        • 2013-01-27
        • 2021-01-13
        • 2017-07-22
        • 2021-11-04
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        相关资源
        最近更新 更多