【问题标题】:What is the best way to pass multiple string variables to a query string in python3将多个字符串变量传递给python3中的查询字符串的最佳方法是什么
【发布时间】:2020-02-21 03:52:34
【问题描述】:

我需要根据两个字符串参数创建一个动态查询:

description = "This is the description"
comment = "This is the comment"
query = "insert into case(desc, comm) value(description, comment)"

注意: 描述评论中可能有单引号双引号

如何使用格式化的 %s 生成查询字符串?

非常感谢。

更新:

感谢 Green Cloak Guy(他/她的回答有未成年人需要纠正),正确的查询是:

query = f"插入 case(description,comment) value(\'{description}\', \'{comment}\')"

【问题讨论】:

    标签: python-3.x string-concatenation


    【解决方案1】:

    使用 f 字符串。

    query = f"insert into case({description}, {comment}) value({description}, {comment})"
    

    不要使用任何类型的字符串格式来执行实际的数据库查询 - 这会导致您遇到 SQL 注入问题。请改用能够正确清理数据的数据库库。

    但如果您需要做的只是将一些变量解析为字符串,这比其他语言倾向于使用的% 格式更灵活(从技术上讲,这在python 中仍然可以通过"some_string %s %s %s" % (str1, str2, str3)" 使用)

    【讨论】:

    • 谢谢,值部分,都应该单引号,
    猜你喜欢
    • 1970-01-01
    • 2017-11-15
    • 2012-06-25
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多